-->

Conditionally show items of Nav widget

2019-05-14 13:48发布

问题:

I want to add a condition to menu items so when a user logs in, he will see menu depending on his user_type. Here is my code.

Nav::widget([
    'encodeLabels' => false,
    'options' => ['class' => 'sidebar-menu'],
    'items' => [
    // I want to insert condition here
    [
        'label' => '<span class="fa fa-fw fa-globe"></span> Menu1',
        'url' => ['/menu1'],
    ],
    [
        'label' => '<span class="fa fa-fw fa-list-alt"></span> Menu2',
        'url' => ['/menu2'],
    ],
]);

Some users can access the menu1 and others can access only the menu2.

回答1:

1) For single item use visible property (info is available here):

[
    'label' => '<span class="fa fa-fw fa-globe"></span> Menu1',
    'url' => ['/menu1'],
    'visible' => $condition,
],

2) As an alternative you can build array before rendering the widget and conditionally include / exclude some items of array dependending on conditions.

$items = [];

if ($condition) {
    $items[] = ...
} else {
    ...
}

echo Nav::widget([
    'items' => $items,
]);

See for example how menu items are formed in advanced template frontend layout.



回答2:

I made something like this by extending Nav class, using own access check function.


class AccessNav extends Nav
{
    public function renderItem($item)
    {
        $url = ArrayHelper::getValue($item, 'url', '#');
        if( PermissionManager::checkAccessByUrl($url))
        {
            return parent::renderItem($item);
        }
    }
}