How to put
  • in navigation menu
  • 2019-10-02 10:13发布

    问题:

    I am working in Yii and am suddenly stuck in this dilemma. The thing is, till this point I was using CMenu and when working with Bootstrap, I was using TbMenu.

    However, in this current project, we have created entirely a different menu with lots of new spans and divs inside, so integrating it with the current TbMenu or Cmenu was proving to be very difficult, so we are putting up the menu HTML as is in the main layout. However, now as I visit any view, it should put the appropriate "active" class in the menu list item.

    TbNavbar and CMenu were able to achieve this automatically, however I am not able to implement it for my views.

    For example :

    I have this in as my navbar :

    So when I visit "someController/actionSomthing" like so :

    www.localhost.com/someController/actionSomthing

    <nav>
    <ul id="blah">
    <li class="active"><a href ="#" >Something</a></li>
    <li><a href ="#" >Something else</a></li>
    <li><a href ="#" >another something</a></li>
    </ul>
    </nav>
    

    So basically when I visit the specific action/Controller : it should put the class = "active" in the li tag.

    Please help.

    Regards,

    回答1:

    You could try this if you want a JS/jQuery solution:

    $(function() {
        var loc = window.location.href;
        $('#blah li').each(function() {
            var link = $(this).find('a:first').attr('href');
            if(loc.indexOf(link) >= 0)
                $(this).addClass('active');
        });
    });
    


    回答2:

    I'm using this class for li items:

    class="<?php echo (Yii::$app->controller->route == 'site/index') ? 'active' : '' ?>"
    

    Also you could use Yii::$app->controller->id for direct links.



    回答3:

    TbMenu is inherit from CMenu. In the current project use active:

    <?php $this->widget('bootstrap.widgets.TbNavbar', array(
        'collapse'=>true,
        'htmlOptions'=>array('role'=>'navigation'),
        'items'=>array(
            array(
                'class'=>'bootstrap.widgets.TbMenu',
                'items'=>array(
                    array(
                        'label'=>'Consultas',
                        'url'=>array('/someController/actionSomthing'),
                        'visible'=>Yii::app()->user->checkAccess('someController'),
                        'active'=>Yii::app()->controller->id=='someController'
                    ),
                ),
            ),
        ),
    )) ?>