视图变量在模板中不可访问

时间:2018-12-16 14:16:50

标签: php cakephp cakephp-3.0

在我的PagesController :: display()中,我有以下代码:

class PagesController extends AppController {

    public function display(...$path) {
        $count = count($path);
        if (!$count) {
            return $this->redirect('/');
        }
        if (in_array('..', $path, true) || in_array('.', $path, true)) {
            throw new ForbiddenException();
        }
        $page = $subpage = null;

        if (!empty($path[0])) {
            $page = $path[0];
        }
        if (!empty($path[1])) {
            $subpage = $path[1];
        }
        $this->set(compact('page', 'subpage'));

        try {
            $this->render(implode('/', $path));
        } catch (MissingTemplateException $exception) {
            if (Configure::read('debug')) {
                throw $exception;
            }
            throw new NotFoundException();
        }
        $test = "abc";
        $this->set(compact('test'));
    }
}

这与the standard pages controller几乎相同,我添加了最后两行。

我的home.ctp模板包含:

<?php
var_dump($test);
...

当我访问该站点时,输出:

C:\wamp64\www\site\src\Template\Pages\home.ctp:322:null

这令人困惑,因为调试工具显示该变量已设置:

debug kit variables panel

为什么home.ctp模板中没有测试变量?

1 个答案:

答案 0 :(得分:1)

在设置之前调用渲染

   try {
        $this->render(implode('/', $path)); <----
    } catch (MissingTemplateException $exception) {
        if (Configure::read('debug')) {
            throw $exception;
        }
        throw new NotFoundException();
    }
    $test = "abc";
    $this->set(compact('test')); <-----
}

调用set太晚了-是在模板已使用之后。

为使设置生效,调用必须在调用渲染之前进行,即:

$test = 'abc';
$this->set(compact('page', 'subpage', 'test')); <---

try {
    $this->render(implode('/', $path)); <---
...

为什么变量会显示在DebugKit中?

DebugKit询问控制器实例以获得使用的视图变量-但这运行right at the end of the request。这就是即使模板中没有可用的调试工具包也可以找到它的原因。

相关问题