CakePHP动态信息的布局


CakePHP dynamic information for a layout

我在CakePHP编码一个博客,为了让自己开始与框架。事情是,我有我的网站的布局,在其中我想显示最新的帖子(只要它不是索引页)和标签云在所有情况下。问题是,我不能让每个控制器都传递一个变量到我的布局,这样它就可以渲染它,所以我需要一些更好的方法来查询帖子的Posts模型和标签云的Tags模型,这将是最好的方法?(以避免将太多的逻辑与视图混合)。

视图代码的相关部分如下:

<?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

您可以使用element和RequestAction: like

<>之前//在你的元素中,你可以这样做:$latestPosts = $this->requestAction('controllername/functionname');之前

查看文档获取更多信息

你可以使用不同的布局。

首页布局 -不显示最新帖子

/app/View/Layout/index.ctp 

默认布局 -显示最新的帖子和标签云

/app/View/Layout/default.ctp

默认情况下,Cake将使用默认值。CTP布局,但你可以在控制器中重写该行为:

public function index() {
    // do index stuff
    $this->layout = "index";
}

我还建议将最新的帖子和标签云捆绑到元素中,以便更容易在布局中包含它们。