将此添加到 app/controllers/pages_controller.php
内的 display
函数的末尾后,
// grab all message lists
$this->loadModel('MessageList');
$this->set('messageLists', $this->MessageList->find('all'));
我尝试在 app/views/pages/home.ctp
中访问它
<?php
foreach($messageLists as $messageList) {
print_r($messageList);
}
?>
但我收到警告
Notice (8): Undefined variable: messageLists [APP\views\pages\home.ctp, line 9]
我的 app/config/routes.php
有:
/**
* Here, we are connecting '/' (base path) to controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, /app/views/pages/home.ctp)...
*/
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
/**
* ...and connect the rest of 'Pages' controller's urls.
*/
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
我需要更改哪些内容才能访问主页中的 $messageLists
?谢谢!
最佳答案
在你的 display() 方法的最后?好吧,这是行不通的,因为它在为它设置 View 变量之前调用 render() 并由此渲染页面。所以把你的 set() 调用移到 render() 调用之前。
还有一个进一步的提示:你的实现做得不是很好,除非你想在每个页面上引起额外的查询,甚至不需要显示消息。
看起来您是 CakePHP 初学者,所以我建议您在手册中查找 requestAction() 以及 View 中的元素是如何工作的。这将允许您在任何 View 文件中使用元素和请求操作来显示消息列表,例如 Messages/getListForUser。
关于CakePHP:为主页设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8795369/