如何在 Yii2 中的 $content 之前在主布局页面中传递全局变量 [英] How do I pass a global variable in Main layout page before $content in Yii2

查看:29
本文介绍了如何在 Yii2 中的 $content 之前在主布局页面中传递全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Nav::widget"在 yii2 中创建动态菜单.这是我在主布局页面的菜单部分中的代码:

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 我在应用程序中创建了一个超级控制器components/Controller.php":

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 放置在主布局页面 ::

2 Place in the Main Layout Page ::

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

            'items' => Yii::$app->controller->menuItems,

        ]);

非常感谢您的帮助.

推荐答案

例如,您可以创建自己的超级控制器并添加 menuItems 属性:

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 {...}

在你的布局中:

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

这篇关于如何在 Yii2 中的 $content 之前在主布局页面中传递全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆