CakePHP:为主页设置变量

标签 cakephp controller routes cakephp-1.2

将此添加到 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/

相关文章:

jquery - 如何使用 jquery 禁用 cakephp 中的 poSTLink?

model-view-controller - Codeigniter Controller 间通信

javascript - Express js 将应用程序变量发送到路由

linux - 如何将 IP 地址添加到 NAT 表 (Linux Debian) - POSTROUTING 链

routes - Cypress URL 匹配查询

mysql - CakePHP:默认数据库正在工作,而测试没有

php - 如何在 PHP/CakePHP 中将关联数组转换为一组 HTML 表格行?

image - ASP.NET MVC3 : Image loading through controller

Javascript/Angular - JS 对象的属性和方法

php - 什么使 CakePHP 安全,我们如何提高它的安全性?