Giest
Giest

Reputation: 495

Yii2: Menu active in different controllers

This is my code:

<?=
     Nav::widget([
          'options' => ['class' =>'nav-pills nav-stacked'],
          'encodeLabels' => false,
          'items' => [
                   [
                    'label' => 'Blog',
                    'url' => ['/blog'],
                    'active' => \Yii::$app->controller->id == 'blog'
                   ],
          ],
     ]);
?>

But I want this menu is active not only when the controller is "blog", but also when it is "category" and "post".

Upvotes: 0

Views: 1680

Answers (1)

Ali MasudianPour
Ali MasudianPour

Reputation: 14459

Change your code like below:

Nav::widget([
      'options' => ['class' =>'nav-pills nav-stacked'],
      'encodeLabels' => false,
      'items' => [
               [
                'label' => 'Blog',
                'url' => ['/blog'],
                'active' => in_array(\Yii::$app->controller->id,['blog','category','post'])
               ],
      ],
 ]);

By above code, your menu item will be considered as active if controller id was one of ['blog','category','post'] values. The only change was:

 'active' => in_array(\Yii::$app->controller->id,['blog','category','post'])

Upvotes: 6

Related Questions