我正在尝试使用“Nav :: widget”在yii2中创建动态菜单。这是我在主布局页面的菜单部分中的代码:
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => [
['label' => 'Home', 'url' => ['/site/index']],
['label' => 'About', 'url' => ['/site/about']],
试图获得解决方案:请看看::
1我在app中创建了一个超级控制器“components / Controller.php”:
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放置在主布局页面::
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => Yii::$app->controller->menuItems,
]);
非常感谢帮助。
答案 0 :(得分:6)
例如,您可以创建自己的超级控制器并添加menuItems
属性:
namespace app\components;
class Controller extends \yii\web\Controller
{
public $menuItems = [
['label' => 'Home', 'url' => ['/site/index']],
['label' => 'About', 'url' => ['/site/about']]
];
}
您的控制器应该扩展它:
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,
]);