Yii2 在 HTML 上的可见性 属性

Yii2 Visibility Property on HTML

我用过

<li class="active" style="visibility:" . <?php User::isSuperAdmin() ?> . "">

但它不起作用。

我知道这样做不对,那么正确的做法是什么? 我希望特定的 <li> 仅对 SuperAdmin 用户可见(条件在 User::isSuperAdmin() 函数内)。

我正在为我的 UI 使用 AdminLTE 资产包,所以我摆脱了 Nav 小部件以实现可折叠的侧边栏。

请有人帮我解决这个问题。

在文件夹 /components 中创建一个新的 WebUser class :

namespace app\components;

class WebUser extends yii\web\User
{
  public function isSuperAdmin()
  {
    //Define here how the superAdmin is defined
    return !$this->isGuest && $this->getIdentity()->username == 'superAdmin';
  }
}

配置文件中(/config/web.php):

'components' => [
    'user' => [
        'class' => 'app\components\WebUser',//The default class id edited
        ...
    ],
  ...
]

在您看来之后:

<li class="active <?= Yii::$app->user->isSuperAdmin() ? '' : 'hidden' ?>">

对于菜单,我建议您使用小部件 yii\widgets\Menu :

echo Menu::widget([
    'items' => [
        ['label' => 'Home', 'url' => ['/site/index']],
        ['label' => '...', 'url' => ['/site/superadmin'], 'visible' => Yii::$app->user->isSuperAdmin()],//Here is a good way
    ],
]);

http://www.yiiframework.com/doc-2.0/yii-widgets-menu.html