2011-11-24 61 views
1

我在CakePHP中編寫了一個博客,以便讓我自己開始使用該框架。事情是,我有我的網站的佈局,我想在其中顯示最新的帖子(只要它不是索引頁)和標籤雲。事情是,我不能讓每個控制器都傳遞一個變量給我的佈局,以便它可以渲染它,所以我需要一些更好的方式來查詢帖子模型和標籤雲的我的標籤模型,將是最好的方式去做呢? (以避免與視圖混合太多的邏輯)。CakePHP佈局的動態信息

的我認爲的代碼中的相關部分如下:

<?php 
if ($this->params['controller'] != 'posts' || $this->params['action'] != 'index') { 
?> 
    <section class="box"> 
     <header> 
      <h3>Latest posts</h3> 
     </header> 
    </section> 
<?php 
// display an unordered list with all the latest posts 
} 
?> 
    <section class="box"> 
     <header> 
      <h3>Tag cloud</h3> 
     </header> 
<!-- display another unordered list with the tags--> 
    </section> 

我使用的,順便說一句,CakePHP的2.0.3

+0

爲什麼不在PostsController或AppController中使用beforeFilter回調來自動將數據傳遞給佈局? – riff

回答

1

您可以用RequestAction一起使用的元素:像

 
//in your element you can do like: 
$latestPosts = $this->requestAction('controllername/functionname'); 

檢查文檔以獲取更多信息

+1

這是[docs for requestAction]部分(http://book.cakephp.org/2.0/en/views.html?highlight=requestaction#passing-variables-into-an-element)。我會認真考慮使用緩存(下一節之後),以便每次有人加載頁面時都不會查詢。 – brism

-1

您可以使用不同的layou TS。

首頁佈局 - 不顯示最新的帖子

/app/View/Layout/index.ctp 

默認佈局 - 並顯示最新的帖子和標籤雲

/app/View/Layout/default.ctp 

默認情況下,蛋糕會使用默認值。 ctp佈局,但您可以在控制器中覆蓋該行爲:

public function index() { 

    // do index stuff 
    $this->layout = "index"; 

} 

我還建議將您的最新帖子和標籤雲捆綁到元素中,以便更輕鬆地將其包含在各個佈局中。

+1

佈局的想法是好的,但因爲佈局之間唯一會有所不同的是那部分,看起來它只是一個廢物 –