Yii2 disable highlighting menu item

2019-07-21 10:33发布

问题:

My main.php code

<?php
        NavBar::begin([
            'brandLabel' => 'Styl-dekoracje.pl',
            'brandUrl' => Yii::$app->homeUrl,
            'options' => [
                'class' => 'navbar-inverse navbar-fixed-top',
            ],
        ]);
        echo Nav::widget([
            'options' => ['class' => 'navbar-nav navbar-right'],
            'items' => [
                ['label' => 'Home', 'url' => ['/site/index']],
                ['label' => 'Orders', 'url' => ['/order']],
                Yii::$app->user->isGuest ?
                    ['label' => 'Login', 'url' => ['/site/login']] :
                    ['label' => 'Logout (' . Yii::$app->user->identity->username . ')',
                        'url' => ['/site/logout'],
                        'linkOptions' => ['data-method' => 'post']],
            ],
        ]);
        NavBar::end();
    ?>

When I click for login/logout or home item its will be highlight. But how can I disable highlighting for SiteController? Where is file who set item as active?

回答1:

Each item insive Nav have active property.

Set it depending on current controller, action, or route.

Example:

[
    'label' => 'Login', 
    'url' => ['/site/login'],
    'active' => $this->context->route == 'site/login',
],

Setting this for site/logout doesn't make sense because it's immediate action with redirect.

Official documentation:

  • Nav $items
  • View $context
  • Controller $route


回答2:

I am not familiar with Yii2, but in Yii there was an activeCssClass option.

'activeCssClass' => ''

The code above disbaled the higlighting of active menu item.



回答3:

You can use Url::to() to make it work. This is just a workaround.

<?php
    NavBar::begin([
        'brandLabel' => 'Styl-dekoracje.pl',
        'brandUrl' => Yii::$app->homeUrl,
        'options' => [
            'class' => 'navbar-inverse navbar-fixed-top',
        ],
    ]);
    echo Nav::widget([
        'options' => ['class' => 'navbar-nav navbar-right'],
        'items' => [
            ['label' => 'Home', 'url' => Url::to(['/site/index'])],
            ['label' => 'Orders', 'url' => Url::to(['/order'])],
            Yii::$app->user->isGuest ?
                ['label' => 'Login', 'url' => Url::to(['/site/login'])] :
                ['label' => 'Logout (' . Yii::$app->user->identity->username . ')',
                    'url' => Url::to(['/site/logout']),
                    'linkOptions' => ['data-method' => 'post']],
        ],
    ]);
    NavBar::end();
?>


标签: menu widget yii2