Yii 2 Menu Usage Examples

Yii 2 Menu Usage Examples

Last updated:

Simplest possible usage (hardcoded items)

echo \yii\widgets\Menu::widget([
    'items' => [
        ['label' => 'Home', 'url' => ['site/index']]
    ]
]);

Note that, in Yii2, $this references the View object, not the Controller anymore so, in order to have variables accessible in the layout (which is where we define menus most of the time), you need to assign the variables coming from the Controller to the View object, for example: (in a view file:)

<?php
    $this->params['menu'] = $menu;
?>
<h1>assets/view</h1>
<!-- the rest of the HTML code for this view -->

Dialogue & Discussion