控制活动菜单项

时间:2016-02-10 11:08:51

标签: yii2

我正在设置一个小页面,所以我从URL中删除了/ site /。大多数页面都是站点控制器上的静态页面,因此看起来更干净。

菜单小部件配置如下:

$menuItems = [
    ['label' => 'Home', 'url' => ['/']],
    ['label' => 'About', 'url' => ['/about']],
    ['label' => 'Projects', 'url' => ['/projects']],
];

配置规则是

'rules' => [
    '<controller:\w+>/<id:\d+>' => '<controller>/view',
    '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
    '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
    '<action:\w+>' => 'site/<action>',
],

现在我的问题是我的菜单项链接不再被标记为活动(css .active)。有什么可以控制的,我该如何改变呢?

5 个答案:

答案 0 :(得分:8)

解决。

像这样更改menuItem

$menuItems = [
    ['label' => 'Home', 'url' => ['/'], 'active' => $this->context->route == 'site/index'],
    ['label' => 'About', 'url' => ['/about'], 'active' => $this->context->route == 'site/about'],
    ['label' => 'Projects', 'url' => ['/projects'], 'active' => $this->context->route == 'site/projects'],
];

答案 1 :(得分:2)

你应该使用'url' => [controller/action]来完成这件事。此配置将被您的规则覆盖。所以,然后会自动添加课程.active

答案 2 :(得分:1)

您可以使用in_array方法检查当前URL。在数组中,我们需要添加菜单处于活动状态的所有URL。

'active' => in_array($this->context->route,['items/index','items/create','items/update']),

如果打开“列表”页面,“创建”页面或“更新”页面,则“项目”菜单将处于活动状态。

我们可以使用Controller id来检查当前控制器

'active' => Yii::$app->controller->id == 'items',

答案 3 :(得分:0)

实际上,正如soovorow所说,它应该与

一起使用
$menuItems = [
    ['label' => 'Home', 'url' => ['/']],
    ['label' => 'About', 'url' => ['/site/about']],
    ['label' => 'Projects', 'url' => ['/site/projects']],
];

问题是受控名称在

中没有明确说明
$menuItems = [
    ['label' => 'Home', 'url' => ['/']],
    ['label' => 'About', 'url' => ['/about']],
    ['label' => 'Projects', 'url' => ['/projects']],
];

答案 4 :(得分:-1)

我在yii2中使用此代码获取最佳菜单:

\yii\widgets\Menu::widget([
    'submenuTemplate' => "\n<ul class='top-nav-menu'>\n{items}\n</ul>\n",
    'activateParents' => false,
    'activeCssClass' => 'active',
    'id' => 'sandwich-menu',
        ['label' => Yii::t('app', 'Education'), 'url' => ['/site/education'] ],
        [
            'label' => Yii::t('app', 'Entertainment'),
            'url' => '#',
            'items' => [
                ['label' => Yii::t('app', 'Games'), 'url' => ['/site/games']],
                ['label' => Yii::t('app', 'Music'), 'url' => ['/site/music'] ],
                ['label' => Yii::t('app', 'Videos'), 'url' => ['/site/videos'] ],
                ['label' => Yii::t('app', 'Chat & Forum'), 'url' => ['/site/forum'] ],
                ['label' => Yii::t('app', 'Clubs'), 'url' => ['/site/clubs'] ]
            ]
        ],
        ['label' => Yii::t('app', 'News'), 'url' => ['/site/news']],
        ['label' => Yii::t('app', 'Contact'), 'url' => ['/site/gencol'] ]
    ]
])