Laravel active menu item for url included parameters

前端 未结 10 2317
暖寄归人
暖寄归人 2020-12-28 14:43

I\'m trying to set active class in my list item, but it doesn\'t work.

My code in blade:

@foreach($data as $site)
  
相关标签:
10条回答
  • 2020-12-28 15:00

    Make a function in helper.

    function activeMenu($uri = '') {
        $active = '';
        if (Request::is(Request::segment(1) . '/' . $uri . '/*') || Request::is(Request::segment(1) . '/' . $uri) || Request::is($uri)) {
            $active = 'active';
        }
        return $active;
    }
    

    Use it in sidebar.

    <li class="{{ activeMenu('dashboard') }}"></li>
    <li class="{{ activeMenu('student') }}"></li>
    <li class="{{ activeMenu('teacher') }}"></li>
    
    0 讨论(0)
  • 2020-12-28 15:01

    Use short if. Example:

    <a href="#" class="{{ (\Request::route()->getName() == 'this.route') ? 'active' : '' }}">
    
    0 讨论(0)
  • 2020-12-28 15:04

    I am currently using Laravel 5.6.* and my solution is:

    <a href="#" class="nav-link {{ request()->is('users*') ? 'active' : '' }}">Users</a>
    
    0 讨论(0)
  • 2020-12-28 15:07

    I am using Laravel 7 and Bootstrap Dropdown. So there are several collapse items that depend on the link, this works:

    <li class="nav-item {{ Route::is('users.*') || Route::is('user.*')  ? 'active' : '' }}">
    
    0 讨论(0)
  • 2020-12-28 15:08

    Use is() method. For example:

    <li class="{{ request()->is('sites/*/edit') ? 'active' : '' }}"
    
    0 讨论(0)
  • 2020-12-28 15:20

    Laravel 7+

    For named routes with prefixes like admin or admin.view or admin.edit etc...

    <li class="{{ Str::startsWith(Route::currentRouteName(), 'admin')) ? 'active' : '' }}">...</li>
    

    A bit verbose but you can look into making a custom function like is_active('admin')

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