CakePHP:设置主页变量

Gar*_*ett 3 controller routes cakephp cakephp-1.2

将其添加到我display函数的末尾之后app/controllers/pages_controller.php

    // grab all message lists
    $this->loadModel('MessageList');
    $this->set('messageLists', $this->MessageList->find('all'));
Run Code Online (Sandbox Code Playgroud)

我尝试app/views/pages/home.ctp像这样访问它

<?php
        foreach($messageLists as $messageList) {
            print_r($messageList);
        }
    ?>
Run Code Online (Sandbox Code Playgroud)

但是我得到警告

Notice (8): Undefined variable: messageLists [APP\views\pages\home.ctp, line 9]
Run Code Online (Sandbox Code Playgroud)

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'));
Run Code Online (Sandbox Code Playgroud)

我需要更改什么以便可以访问$messageLists主页?谢谢!

bur*_*zum 5

在display()方法的最后?好吧,这是行不通的,因为它在设置视图变量之前,先调用render()并由此渲染页面。因此,将set()调用移到render()调用之前。

还有一个进一步的提示:您的实现不是很好,只是您希望在每个页面上引起甚至不需要显示消息的其他查询。

看来您是CakePHP的初学者,所以我建议您在手册中查找requestAction()以及视图中的元素如何工作。这将允许您通过使用元素和请求操作(例如Messages / getListForUser)在任何视图文件中使用元素来显示消息列表。