Skip to main content

Nav - Menu's

Example menu.

Menu 1 contain a confirmation dialog, menu 2 contains an external URL/Link.

<?php

echo Nav::widget([
    'encodeLabels' => false,
    'items' => [
        [   'label' => 'Menu1',
            'visible' => (isset(Yii::$app->user->identity->role) && Yii::$app->user->identity->role == 'admin'),
            'items' => [
                 ['label' => 'Item1', 'url' => ['/control/action'] ],
                 ['label' => 'Item2', 'url' => ['/control/action'] ],
                 ['label' => 'Item3', 'url' => ['/control/action'] ],
                 [  'label' => 'Item4',
                     'url' => ['/control/action'],
                      'linkOptions' => array('onclick'=>'return confirm("Are you sure? ")'),
             ],
                 ['label' => '-----------------------------------'],
                 ['label' => 'Item1', 'url' => ['/control/action'] ],
            ],
            'options' => ['class' => 'nav-item']
        ],
      
   		[   'label' => 'Menu2',
            'visible' => (isset(Yii::$app->user->identity->role) && Yii::$app->user->identity->role == 'admin'),
            'items' => [
                 ['label' => 'Item1', 'url' => ['/control/action'] ],
                 ['label' => 'Item2', 'url' => ['/control/action'] ],
                 [  'label' => 'Item3',
                    'url' => 'https://server.com/page1',
                    'template'=> '<a href="{url}" target="_blank">{label}</a>',
                    'linkOptions' => ['target' => '_blank'],
                  ],
            ],
            'options' => ['class' => 'nav-item']
        ],
    ],
]);
Split menu from main.php
// In main.php

// remove the use *navbar* lines (2)

<header>
	// remove menu here and replace it with this line
    <?php echo Yii::$app->view->renderFile('@app/views/layouts/menu.php'); ?>
</header>

// now you can put your menu in the file menu.php (same directory)
// menu.php

<?php

use yii\bootstrap4\Nav;
use yii\bootstrap4\NavBar;
use yii\bootstrap4\Html;

NavBar::begin([
    'brandLabel' => Yii::$app->name,
    'brandUrl' => Yii::$app->homeUrl,
    'options' => [
        'class' => 'navbar navbar-expand-md navbar-dark bg-dark fixed-top',
    ],
]);

echo Nav::widget([
    'options' => ['class' => 'navbar-nav'],
    'items' => [
...
...