Yii2. If condition inside array

时间:2016-04-25 09:11:47

标签: php arrays yii2

Default Yii2 layout has navbar with shorthand if condition for login menu entry

echo Nav::widget([
    'options' => ['class' => 'navbar-nav navbar-right'],
    'items' => [
        /*
        ...
        some items
        ... 
        */
        Yii::$app->user->isGuest ? (
            ['label' => 'Login', 'url' => ['/site/login']]
        ) : (
            '<li>'
            . Html::beginForm(['/site/logout'], 'post')
            . Html::submitButton(
                'Logout (' . Yii::$app->user->identity->username . ')',
                ['class' => 'btn btn-link']
            )
            . Html::endForm()
            . '</li>'
        ),
    ],
]);

How I can add few entries into this condition? This doesn't work(syntax error - unexpected ',')

Yii::$app->user->isGuest ? (
            ['label' => 'Login', 'url' => ['/site/login']],
            ['label' => 'Register', 'url' => ['/site/register']]
) :

1 个答案:

答案 0 :(得分:1)

Seems easier to add items to the array outside of the widget definition.

$items = /* some items */;
if (Yii::$app->user->isGuest) {
    $items[] = ['label' => 'Login', 'url' => ['/site/login']];
    $items[] = ['label' => 'Register', 'url' => ['/site/register']];
} else {
    $items[] = ['your html'];
}

echo Nav::widget([
    'options' => ['class' => 'navbar-nav navbar-right'],
    'items' => $items,
]);