简体   繁体   English

Cake PHP的多个视图页面可以访问相同的变量

[英]Cake PHP multiple view pages have access to the same variables

I'm doing the blog tutorial (CakePHP 2.4.1) and have a question. 我正在写博客教程(CakePHP 2.4.1),有一个问题。

What is the reasoning ( and why) does the index.ctp page require me to loop through the $posts variable to get data but the view.ctp file lets me just grab $post without looping? index.ctp页面要求我循环遍历$ posts变量以获取数据是什么原因(以及为什么),但是view.ctp文件允许我仅获取$ post而不会循环? I deleted the following action in PostController.php and still could render the view.ctp file so I figure the two are not connected. 我在PostController.php中删除了以下操作,仍然可以渲染view.ctp文件,因此我认为两者未连接。

 public function index() {
    $this->set('posts', $this->Post->find('all'));
}

You're setting post in both of the controller's functions: 您要在两个控制器功能中都设置post:

index() 指数()

$this->set('posts', $this->Post->find('all'));

view() 视图()

$post = $this->Post->findById($id);
$this->set('post', $post);

It would be odd if you weren't able to access the variables, but it seems everything is functioning as normal in your example 如果您无法访问变量,那将很奇怪,但是在您的示例中,似乎一切正常

Edit: 编辑:

You loop through the array in the index because you have multiple posts inside of an array. 您在索引中遍历数组,因为数组中有多个帖子。 And in the view you're setting only a singular array containing one post so there is no need to loop through anything, you're able to grab the elements directly. 并且在视图中,您只设置了一个包含一个帖子的奇异数组,因此无需遍历任何内容,您可以直接获取元素。

    $this->set('posts', $this->Post->find('all')); 

This will return an array of posts - notice the find('all') 这将返回一组帖子-注意find('all')

    $this->set('post', $this->Post->findById($id));

This will return a single post by the passed $id parameter. 这将通过传递的$ id参数返回单个帖子。

The reason you have to loop through $posts is because its an array (returned by the find all), where $post is just a single post returned by findById) 您必须遍历$ posts的原因是因为它是一个数组(由全部查找返回),其中$ post只是findById返回的单个帖子)

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

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