How do I pass a global variable in Main layout page before $content in Yii2
yii, yii-components, yii-extensions, yii2
Solution
You could, for example, create your own super controller and add a `menuItems` attribute :
namespace app\components;
class Controller extends \yii\web\Controller
{
public $menuItems = [
['label' => 'Home', 'url' => ['/site/index']],
['label' => 'About', 'url' => ['/site/about']]
];
}
Your controllers should extend it :
namespace app\controllers;
use app\components\Controller;
class MyController extends Controller {...}
And in your layout :
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => Yii::$app->controller->menuItems,
]);
Problem
I am trying to create dynamic menu in yii2 using "Nav::widget". Here is my code in menu section in main layout page: ``` echo Nav::widget([ 'options' => ['class' => 'navbar-nav navbar-right'], 'items' => [ ['label' => 'Home', 'url' => ['/site/index']], ['label' => 'About', 'url' => ['/site/about']], ``` Trying to get the solution: Please have a look:: 1 I have created a super controller "components/Controller.php" in app: ``` namespace app\components; use app\models\MenuPanal; class Controller extends \yii\web\Controller { public $menuItems = []; public function init(){ $items = MenuPanal::find() ->orderBy('id') ->all(); $menuItems = []; foreach ($items as $key => $value) { $this->menuItems[] = ['label' => $value['c_type'] , 'url' => ['#']]; } parent::init(); } } ``` 2 Place in the Main Layout Page :: ``` echo Nav::widget([ 'options' => ['class' => 'navbar-nav navbar-right'], 'items' => Yii::$app->controller->menuItems, ]); ``` Helps are highly appreciated.