2012-06-29 51 views
0

我一直在尋找一種靈活的方式來在不同的頁面中生成不同的側邊欄。目標是將自定義鏈接傳遞到每個側欄。模板庫似乎對我的應用程序來說過分了,所以我開發了一個簡單的解決方案。我不確定這是否是最佳解決方案。我的問題是你怎麼看?非常感謝您的建議!Codeigniter創建動態側邊欄

。在你的控制器中添加加載你的側邊欄視圖私有函數:

/** 
* The function has 2 arguments. 
* $title is the sidebar widget title. 
* $widget will contain an array of links to be added in the sidebar widget. 
*/ 

private function sidebar($title, $widget) 
{ 
    $widget['title'] = $title; 
    $this->load->view('includes/sidebar', $widget); 
} 

2.在要加載自定義側邊欄的控制器功能,調用私有函數sidebar()和期望的側邊欄數據傳遞到它。

下面是一個名爲edit的控制器函數,用於編輯帖子。在這個例子中,我需要加載的選項欄中查看和刪除後我在:

function edit($post_id = '') 
{ 
    //your code, form validation, etc... 

    //Prepare sidebar widget links 
    //Array key is link url, array value is link name 
    $widget['links'] = array (
     'posts/single/' . $post_id => 'View post', 
     'posts/remove/' . $post_id => 'Remove post' 
    ); 
    $this->sidebar('Options', $widget); //load sidebar 
} 

最後顯示從控制器通過自定義數據的側邊欄視圖:

<div id="sidebar"> 
    <ul> 
     <li class="widget"> 
      <div class="label"><?php echo $title; ?></div> 
      <ul> 
       <?php foreach ($links as $link => $value): ?> 
        <li><?php echo anchor($link, $value); ?></li> 
       <?php endforeach; ?> 
      </ul> 
     </li> 
    </ul> 
</div> 

結論

下面的代碼添加到自定義側邊欄標題和鏈接的所有控制器功能:

$widget['links'] = array (
      'controller/function' => 'Link Name 1', 
      'controller/function' => 'Link Name 2', 
      'controller/function' => 'Link Name 3' 
); 
$this->sidebar('Widget Title', $widget); 

回答

3

我認爲完成它。我不是CodeIgniter的專家,但我可以告訴你,這很好。你應該始終確保的一件事是驗證傳遞給函數的數據。在這種情況下:

private function sidebar($title=FALSE, $widget=FALSE) { 
    if ($title && $widget) { 
     //process 
    } 
    else 
     return FALSE 
    } 
} 

另一種方式來做到這一點僅僅是鏈接傳遞給模板(沒有側邊欄模板,但你的主模板:

$data['sidebar'] = array('link/link'=>'My Link'); 
$this->load->view('mytemplate', $data); 

而且在模板您加載側邊欄模板,並將它傳遞的數據:

<html> 
<!--All my html--> 
<?php $this->load->view('includes/sidebar', $data['sidebar']); ?> 
</html> 

這僅僅是另一個選擇,但是你做了什麼就好了

+0

日。這是一個很好的選擇。我通常將函數參數設置爲一個空字符串'function sidebar($ title ='',$ widget ='''。我以前沒有嘗試過使用'FALSE'。私有函數對靈活性很有幫助。想要更改視圖網址,您可以在專用功能中更改它,而不必編輯每個功能。 – CyberJunkie