在模板中无法访问视图变量

View variable is not accessible in template

在我的 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

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

为什么测试变量在 home.ctp 模板中不可用?

渲染在设置前被调用

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

对 set 的调用太晚了 - 在模板已经被使用之后。

要产生任何效果,set 调用必须在调用 render 之前,即:

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

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

为什么变量会出现在 DebugKit 中?

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