How do I pass a global variable in Main layout page before $content in Yii2

谁说我不能喝 提交于 2019-12-19 04:14:07

问题


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.


回答1:


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,
]);


来源:https://stackoverflow.com/questions/23987416/how-do-i-pass-a-global-variable-in-main-layout-page-before-content-in-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!