突出显示数组中的活动链接

时间:2012-02-17 11:14:00

标签: php templates

我想根据你的页面申请class="active"。最好的方法是什么?

例如:

在构造函数中,它创建一个链接名称和地址数组。

class OrderController extends Controller {

   public $data = array();

   private __construct() {
        $this->data['sidebar'] = array(
            'New Orders' => '/admin/order',
            'Processing Orders' => '/admin/order/processing',
            'Completed Orders' => '/admin/order/completed',
    );


   public function actionIndex($status) {
        $data = $this->data;
        if ($status == "processing") {
         //how to apply class="active" when you on the order/processing page?
         //Apply active in the data['sidebar'] array 
        }

        $view = new view('orders.php', $data);
        $view->render();
    }
  } 

数组传递到actionIndex()并渲染orders.php

在orders.page中,我有类似的内容:

<?php foreach ($sidebar as $name => $link): ?>
    <li>
      <strong><a href="<?php echo $link; ?>"><?php echo $name; ?></a></strong>
   </li>
<?php endforeach; ?>

我想在class="active"代码中添加li

2 个答案:

答案 0 :(得分:1)

您可以在阵列上构建:

class OrderController extends Controller {

   public $data = array();

   private __construct() {
        $this->data['sidebar'] = array(
            'New Orders' => array( 'url'=>'/admin/order', 'class'=>'' ),
            'Processing Orders' => array( 'url'=>'/admin/order/processing', 'class'=>'' )
            'Completed Orders' => array( 'url'=>'/admin/order/completed', 'class'=>'' ),
    );


   public function actionIndex($status) {
        $data = $this->data;
        if ($status == "processing") {
          $data['sidebar']['Processing Orders']['class'] = 'active';
        }

        $view = new view('orders.php', $data);
        $view->render();
    }
  }

现在你要改变你的foreach:

<?php foreach ($sidebar as $name => $link): ?>
   <li class="<?php echo $link['class']; ?>">
      <strong><a href="<?php echo $link['url']; ?>"><?php echo $name; ?></a></strong>
   </li>
<?php endforeach; ?>

答案 1 :(得分:0)

我的基本想法是:

if ($tatus == "processing") {
    data['active'] = 'processing';
}

...........

<?php foreach ($sidebar as $name => $link): ?>
    <li <?php if ($active == $name) echo class="active"; ?>>
      <strong><a href="<?php echo $link; ?>"><?php echo $name; ?></a></strong>
   </li>
<?php endforeach; ?>

条件基于名称必须处理...随意根据需要进行修改。