jeudi 23 mars 2017

Getting parent menu to stay active

I'm trying to get my parent menu to stay active when I'm on a page that is a "child" of it. For example I have a Stories menu and I would like the stories that get displayed to still have stories menu active.

I've managed to get only the parent menu active when I'm on it but not the child page.

My url root when I'm on the Stories menu looks like this

http://localhost/writers-circle/public/3

and when I'm on a story it looks like this

http://localhost/writers-circle/public/stories/elven-princess

This is my code. I've placed it in a helpers.php file.

function menu_active($id){
    $menu_id = $id;
    $menu = App\Modules\Menus\Models\Menu::with('seo')->where('id', $menu_id)->first();
    $seo_url = $menu->seo;

    foreach($seo_url as $seo){
        $url = $seo['url'];
        if(is_array($url)){
            return in_array(Request::path(), $url) ? 'current' : '';
        }

        return Request::path() == $url ? 'current' : '';
    }

    if(is_array($id)){
        return in_array(Request::path(), $id) ? 'current' : '';
    }

    return Request::path() == $id ? 'current' : '';
}

The code above allows my menu items to have the current class whether it's by id or by url created by the seo table.

This is my menu.blade.php

<nav class="navbar navbar-default">
<div class="container-fluid">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main_menu" aria-expanded="false">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    </button>
  </div>

  <div class="collapse navbar-collapse menubar" id="main_menu">
    <ul class="nav navbar-nav" id="menu">
      @foreach($menus_child as $grandfather)
        <li class="parent {!! menu_active($grandfather->id) !!}">
          {!! Html::link(getSeoLink($grandfather->id), $grandfather->title) !!}
        </li>
      @endforeach
    </ul>
  </div>
</div>



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2nhKClC
via IFTTT

Aucun commentaire:

Enregistrer un commentaire