YII2: How can I create a link/url in a Menu item t

2019-06-01 05:18发布

I am using the YII2 Menu Widget and did not find the solution to add attribute options like class , target on created link.

My code is below:

echo Menu::widget(
[
    'options' => [
        'class' => 'sidebar-menu'
    ],

    'items' => [

        [
            'label' => Yii::t('backend', 'Admin'),
            'url' => Yii::$app->homeUrl,
            'icon' => 'fa-list-alt',
            'options' => [
                'class' => 'treeview',
            ],
            'items' => [
                [
                    'label' => Yii::t('backend', 'External link'),
                    'url' => 'http://google.com',
                    'icon' => 'fa-list-alt',
                    'options' => [
                    'target' => '_blank',
                    ],
                ],
            ]
        ],                

    ]
]
 );

Option target is not added on generated link.

4条回答
We Are One
2楼-- · 2019-06-01 05:33

You can add any url. For Example,

echo Menu::widget([
    'items' => [
        ['label' => 'Home', 'url' => ['http://www.google.com']],
        ['label' => 'About', 'url' => ['site/about']],
     ['label' => 'Contact', 'url' => ['site/contact']],
    ],
    'options' => [
                    'class' => 'navbar-nav nav',
                    'id'=>'navbar-id',
                    'style'=>'font-size: 14px;',
                    'data-tag'=>'yii2-menu',
                ],
]);
查看更多
相关推荐>>
3楼-- · 2019-06-01 05:39

add the target like below through the template setting. The Options you have set in your code are the Html Options of the li element and not the link options.

'items' => [
    [
       'label' => Yii::t('backend', 'External link'),
       'url' => 'http://google.com',
       'icon' => 'fa-list-alt',
       'template'=> '<a href="{url}" target="_blank">{label}</a>',
    ],
]
查看更多
狗以群分
4楼-- · 2019-06-01 05:44

If you want to keep the icon in your menu:

'template'=> '<a href="{url}" target="_blank">{icon}{label}</a>'

As regards the class you must specify it in the options key:

[
    'label' => 'Debug', 
    'icon' => 'fa fa-dashboard', 
    'url' => ['/debug'],
    'options' => ['class' => 'special'],
    'template'=> '<a href="{url}" target="_blank">{icon}{label}</a>',
],

gives the following menu:

<li class="special">
    <a target="_blank" href="your_site_url_here/index.php?r=debug">
        <i class="fa fa-dashboard"></i>
        <span>Debug</span>
    </a>
</li>
查看更多
Root(大扎)
5楼-- · 2019-06-01 05:58

Suggestions above do not seem to be working (in my case), an alternative solution is:

'linkOptions' => ['target' => '_blank']

For example

[
    'url' => \Yii::$app->user->identity->getBlogLink(),
    'linkOptions' => ['target' => '_blank']  ,
    'label' => \Yii::t('app', 'Blog')
]
查看更多
登录 后发表回答