Yii2 Nav Bar add images in menu items

Muhammad Shahzad picture Muhammad Shahzad · Jul 22, 2016 · Viewed 9.8k times · Source

Is it possible to add images in Yii2 Bootstrap Nav Bar menu items? In official doc I haven't found any option.

I want to show images instead of Label text!

Nav Bar code is.

<?php
    NavBar::begin([
        'brandLabel' => 'My Company',
        'brandUrl' => Yii::$app->homeUrl,
        'options' => [
            'class' => 'navbar-inverse navbar-fixed-top',
        ],
    ]);

   $menuItems = [];

   $menuItems[] = [
            'label' => Yii::t('app','Language'),
            'items' => [
                [
                  'label' => 'English', 
                  'url' => ['site/language','set'=>'en'],
                ],

                '<li class="divider"></li>',

                [
                  'label' => 'Danmark',
                  'url' => ['site/language','set'=>'da'],
                ],

              ],
      ];

Answer

scaisEdge picture scaisEdge · Jul 22, 2016

if an icon you can use icon

   $menuItems[] = [
        'label' => Yii::t('app','Language'),
        'items' => [
            [
              'label' => 'English', 
              'url' => ['site/language','set'=>'en'],
              'icon'=> 'cog',
            ],

if an img and the html code in label

  $menuItems[] = [
        'label' => Yii::t('app','Language'),
        'items' => [
            [
              'label' => '<img src="smiley.gif" ><span>sample</span>', 
              'url' => ['site/language','set'=>'en'],
            ],

I use

use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;

and you should set the 'encodeLabels' => false,

        echo Nav::widget([
            'options' => ['class' => 'navbar-nav navbar-right'],
            'items' => $menuItems,
            'encodeLabels' => false,
        ]);