如何在 Yii2 中的 $content 之前在主布局页面中传递全局变量

编程入门 行业动态 更新时间:2024-10-25 04:16:36
本文介绍了如何在 Yii2 中的 $content 之前在主布局页面中传递全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试使用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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-23 19:13:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047566.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:布局   全局变量   页面   如何在   content

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!