您的位置:首页 > 编程语言 > PHP开发

YII的CMenu使用中url和active的问题

2016-06-10 00:00 561 查看
摘要: 只是讨论YII的CMenu使用中url和active的一个特殊情况:
'url'=>array('/posts/index&postType=c')
'url'=>array('/posts/index&postType=php')
不详细介绍CMenu的使用

YII的CMenu一般的使用方法如下:

$this->widget('zii.widgets.CMenu',array(
'linkLabelWrapper' => 'span',
'items'=>array(
array('label'=>'Home', 'url'=>array('post/index'),'active'=>$this->id=='default'?true:false),
array('label'=>'About', 'url'=>array('site/page'),'active'=>$this->action->id=='page'?true:false),
array('label'=>'Contact', 'url'=>array('site/contact'),'active'=>$this->action->id=='contact'?true:false),
array('label'=>'Login', 'url'=>array('site/login'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('site/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
));

要获取controller的名称,可以直接使用$this->id。

要获取action的名称,可以使用$this->action->id。

CMenu的具体使用可以参考下面的链接,个人觉得这个链接的内容比其他地方更易懂
http://lhj0206.lofter.com/post/1cb9f491_4d2a72c
但是如果URL如下所示:

'url'=>array('/posts/index&postType=c')

'url'=>array('/posts/index&postType=php')

要区分这两个url,就要区分postType的值,但是大部分讲解CMenu的地方都没有说到怎么获取这些值。

这时候要获取postType,可以使用 Yii::app()->request->requestUri 获取到整个URI,然后进行相应操作,比如:

'active'=>(

$this->id=='posts'

&& $this->action->id=='index'

&& strpos(Yii::app()->request->requestUri,'php')

) ? true : false,

上面代码的意思是,当controller为posts,action为index,URI中包含php时,active才为true。

这是直接对URI进行比较,我们也可以通过URI得到postType的具体值后再做比较。

这里使用了strpos方法,这个方法的使用可以参考下面的链接:
http://www.w3school.com.cn/php/func_string_strpos.asp
感谢stackoverflow的一个回答:
http://stackoverflow.com/questions/9802662/yii-how-to-highlight-the-current-menu-item
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  YII CMenu active url