访问 NavBar 项中的控制器变量

access controller variable in NavBar items

在我位于导航栏的布局文件中,我有一个名为 message 的项目。我想在上面显示消息数量 实际上我可以构建一个隐藏元素并在其中显示我的变量并再次获取它并将其附加到带有 Jquery 的项目中的空元素......但我想知道更简单和如果有任何更短的方法

我像这样在 beforeAction 中获取消息计数

 namespace app\component;

    class Controller extends \yii\web\Controller {

        public function beforeAction($event)
        {

            $this->layout = "site-developer";

            $username = Yii::$app->user->identity->username;
            $model = Messages::find()->select('*')->where(['towho' => $username])->count();

            $this->view->params['model'] = $model;


            return parent::beforeAction($event);
        }


    }

在布局中我的导航栏代码是这样的

<?php
NavBar::begin([
    'brandOptions' => [
        'class' => 'hide-on-med-and-down'
    ],
    'brandLabel' => 'My Company',
    'brandUrl' => Yii::$app->homeUrl,
    'fixed' => false,
    'wrapperOptions' => [
        'class' => 'nav-wrapper'
    ],
]);

$menuItems = [
    ['label' => '<i class="material-icons">search</i>'],
    ['label' => '<i class="material-icons">email</i>'],
    ['label' => '<i class="material-icons">view_module</i>'],
    ['label' => '<i class="material-icons">refresh</i>'],
    ['label' => '<i class="material-icons">more_vert</i>', 'items' => [  // will be rendered as dropdown
        ['label' => 'Home', 'url' => ['/site/index']],
        ['label' => 'About', 'url' => ['/site/about']],
        ['label' => 'Home', 'url' => ['/site/about']],
        ['label' => 'Contact', 'url' => ['/site/contact']]
    ]],

];
if (Yii::$app->user->isGuest) {
    $menuItems[] = ['label' => '<i class="fa fa-sign-in"></i>', 'url' => ['/site/signup'], 'class'=>'aa'];
    $menuItems[] = ['label' => '<i class="fa fa-sign-in"></i>', 'url' => ['/site/login'], 'class'=>'aa'];
} else {
    $menuItems[] = '<li>'
        . Html::beginForm(['/site/logout'], 'post')
        . Html::submitButton(
            '<i class="fa fa-sign-out"></i> (' . Yii::$app->user->identity->username . ')',
            ['class' => 'badge red lighten-2 user-dash']
        )
        . Html::endForm()
        . '</li>';
}

echo Nav::widget([
    'encodeLabels' => false,
    'options' => ['class' => 'right'],
    'items' => $menuItems,

]);

NavBar::end();
?>

有什么方法可以在此处导航栏的菜单项中使用用户消息编号 ['label' => '<i class="material-icons">email</i>'],

???

我们可以通过

访问该号码
<?php

$model = $this->params['model'];

echo $model; ?>

如果您已经 'encodeLabels' => false,Nav::widget 中,您可以在标签内容

中连接值
['label' => '<i class="material-icons">email(' . $this->params['model']. ')</i>'],