我遇到类似这个问题的问题
How to identify active menu link in CakePHP
我的default.ctp文件中有一个页面,我想在链接上添加“活动”类。我如何识别页面的当前网址然后在链接上应用该类..我已经按照答案那里
$url = $this->Html->url('INPUT_THE_URL') ;
$active = $this->request->here == $url? true: false;
我不知道我怎么能在我的代码中这样做...很抱歉,因为我是cakephp的新手..这是我的代码
**default.ctp file**
<li>
<?php echo $this->Html->link('Dashboard', array('controller'=>'users','action' => 'controlpanel'), array('title' => 'Dashboard','class' => 'shortcut-dashboard'));?></li>
<li> <?php echo $this->Html->link('Contacts', array('controller'=>'contacts','action' => 'index'), array('title' => 'Contacts','class' => 'shortcut-contacts'));?></li>
我想添加一个类似li的课程
<li class = 'active''>
答案 0 :(得分:12)
这是一个简单的逻辑如下
<li class="<?php echo (!empty($this->params['action']) && ($this->params['action']=='controlpanel') )?'active' :'inactive' ?>">
<?php echo $this->Html->link('Dashboard', array('controller'=>'users','action' => 'controlpanel'), array('title' => 'Dashboard','class' => 'shortcut-dashboard'));?>
</li>
<li class="<?php echo (!empty($this->params['action']) && ($this->params['action']=='index') )?'active' :'inactive' ?>">
<?php echo $this->Html->link('Contacts', array('controller'=>'contacts','action' => 'index'), array('title' => 'Contacts','class' => 'shortcut-contacts'));?></li>
答案 1 :(得分:7)
如果你有一个不同的控制器并且你声明了一个具有相同名称的方法,并且上面的代码不起作用,那么你可以执行以下操作:
<li class="<?php echo (($this->params['controller']==='hotels')&& ($this->params['action']=='view') )?'active' :'' ?>" >
<?php echo $this->Html->link('Hotels', array('controller' => 'hotels', 'action' => 'view')); ?>
</li>
<li class="<?php echo (($this->params['controller']==='packages')&& ($this->params['action']=='view') )?'active' :'' ?>" >
<?php echo $this->Html->link('Packages', array('controller' => 'packages', 'action' => 'view')); ?>
</li>
此处 view 方法在不同的控制器中声明。我希望它对你有所帮助。
答案 2 :(得分:1)
不要复活死去的帖子,但这就是我所做的(我相信它更清洁,更快,更易于管理)
我创建了一个包含页面数组的元素,然后检查数组中的每个项目以查看它是否是当前页面。如果是,我添加活动类。
然后我可以从任何地方调用此元素。
// Changed the line below to a multi-dimensional array to cater for different controllers and actions
//$mypages = array('Home','About','Pricing','FAQs','Contact');
$mypages = array(
array('controller'=>'controller1','action'=>'action1','name'=>'name1'),
array('controller'=>'controller2','action'=>'action2','name'=>'name2
')
);
foreach ($mypages as $page ){
// Changed to account for controller and action
//$currentPage = isset($this->params['pass'][0]) ?$this->params['pass'][0] : "";
$controller = isset($this->request->params['controller'])?$this->request->params['controller']: "";
$action= isset($this->request->params['action'])?$this->request->params['action']: "";
if (strtolower($page['controller']) == $controller && strtolower($page['action']) == $action) {
echo "<li class='active'>" . $this->Html->link($page,array("controller"=>"pages", "action"=>strtolower($page))) . "</li>" ;
}
else {
echo "<li>" . $this->Html->link($page,array("controller"=>"pages", "action"=>strtolower($page))) . "</li>";
}
}