问题
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