简体   繁体   English

CakePHP动态信息的布局

[英]CakePHP dynamic information for a layout

I am coding a blog in CakePHP in order to get myself started with the framework. 我正在CakePHP中编写博客,以使自己开始使用该框架。 The thing is, I've got my website's layout, in which I want to display the latest posts (as long as its not the index page) and a tag cloud in all cases. 问题是,我已经有了网站的布局,在这里我想显示最新的帖子(只要不是索引页面)和所有情况下的标签云。 The thing is, I can't just go having every controller pass a variable to my layout so that it can render it, so I need some better way to query the Posts model for my posts and my Tags model for the tag cloud, which would be the best way to go about it? 关键是,我不能仅仅让每个控制器将一个变量传递到我的布局以使其能够呈现它,所以我需要一种更好的方法来查询我的帖子的Posts模型和标签云的Tag模型,这将是最好的方法吗? (so as to avoid mixing too much of the logic with the view). (以免将过多的逻辑与视图混淆)。

The relevant part of my view's code is as follows: 我视图代码的相关部分如下:

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

I am using, by the way, CakePHP 2.0.3 顺便说一下,我正在使用CakePHP 2.0.3

You could use element along with RequestAction: like 您可以将元素与RequestAction一起使用:

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

Check documentation for more information 查看文档以获取更多信息

You can use different layouts. 您可以使用不同的布局。

Homepage layout - doesn't display latest posts 主页布局 -不显示最新帖子

/app/View/Layout/index.ctp 

Default layout - does display latest posts and tag cloud 默认布局 -不显示最新帖子和标签云

/app/View/Layout/default.ctp

By default, Cake will use the default.ctp layout but you can override that behaviour in your controller: 默认情况下,Cake将使用default.ctp布局,但是您可以在控制器中覆盖该行为:

public function index() {

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

}

I'd also recommend bundling your latest posts and tag cloud into elements to make it easier to include them across layouts. 我还建议您将最新的帖子和标签云捆绑到元素中,以使其更容易在布局中包括它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM