Setting Bootstrap navbar active class in Laravel 5

前端 未结 13 2044
温柔的废话
温柔的废话 2020-12-23 16:34

I\'ve been wondering around looking for solutions, but can\'t really understand especially when creating helpers. I\'m new in Laravel and I want a simple or if not a detaile

相关标签:
13条回答
  • 2020-12-23 16:57

    Request::path() returns the request uri, for example: http://localhost/programs , will return programs, so you can do this:

     <li class="{{ Request::path() ==  'programs' ? 'active' : ''  }}">
                        <a href="{{ url('programs') }}"></i> Programs</a>
                    </li>
    
    0 讨论(0)
  • 2020-12-23 17:01

    Your code is working fine, but you have to use it for every link that can be active. It is better to return only class name, not class="..." so you can add other classes.

    Be careful when using * at the end (about*). If you use /* for home page then it will always be marked as active (because every other page starts with /).

    <ul class="nav nav-pills pull-right">
        <li class="{{ Request::is('/') ? 'active' : '' }}">
            <a href="{{ url('/') }}">Home</a>
        </li>
        <li class="{{ Request::is('about') ? 'active' : '' }}">
            <a href="{{ url('about') }}">About Us</a>
        </li>
        <li class="{{ Request::is('auth/login') ? 'active' : '' }}">
            <a href="{{ url('auth/login') }}">Login</a>
        </li>
    </ul>
    

    You can also move {{ Request::is('/') ? 'active' : '' }} to helper function/method.

    0 讨论(0)
  • 2020-12-23 17:04

    I think this would be simple, and it works for me.

    <li class="{{ Request::segment(1)=='vehicles' ? 'active' : '' }}">
       <a href="/vehicles">Vehicles</a>
    </li>
    
    0 讨论(0)
  • 2020-12-23 17:07

    Throw this in your helper.php

    function set_active($path, $active = 'active') {
    
        return call_user_func_array('Request::is', (array)$path) ? $active : '';
    
    }
    

    Use it like so

    <li class="{{ set_active(['about*']) }}"><a href="{{ url('about') }}">About Us</a>
    

    You can pass a single string to a route or multiple and wildcards.

    See more detail on Laravel Trick

    0 讨论(0)
  • 2020-12-23 17:08

    The solution given by @Daniel Antos is best answer, as I have found. Mr. Danial Antos also warned about using * at the end (about*). Because while using /* for home page then it is always marked as active (because every other page starts with /). So, I have used as follows and it worked fine for me:

    {{ (Request::is('users') || Request::is('users/*') ? 'active open' : '') }}
    
    0 讨论(0)
  • 2020-12-23 17:08

    use Request::is('[level]') ? 'active' : '' In case of multilevel, use:

    Request::is('[level]', '[level]/*') ? 'active' : ''

    0 讨论(0)
提交回复
热议问题