簡體   English   中英

Cake PHP的多個視圖頁面可以訪問相同的變量

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

我正在寫博客教程(CakePHP 2.4.1),有一個問題。

index.ctp頁面要求我循環遍歷$ posts變量以獲取數據是什么原因(以及為什么),但是view.ctp文件允許我僅獲取$ post而不會循環? 我在PostController.php中刪除了以下操作,仍然可以渲染view.ctp文件,因此我認為兩者未連接。

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

您要在兩個控制器功能中都設置post:

指數()

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

視圖()

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

如果您無法訪問變量,那將很奇怪,但是在您的示例中,似乎一切正常

編輯:

您在索引中遍歷數組,因為數組中有多個帖子。 並且在視圖中,您只設置了一個包含一個帖子的奇異數組,因此無需遍歷任何內容,您可以直接獲取元素。

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

這將返回一組帖子-注意find('all')

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

這將通過傳遞的$ id參數返回單個帖子。

您必須遍歷$ posts的原因是因為它是一個數組(由全部查找返回),其中$ post只是findById返回的單個帖子)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM