我正在尝试将一个对象
传递给partial()
View 助手。虽然使用普通变量工作正常,但我无法将对象传递给此函数。
例如,在部分使用 $this->test
时效果很好:
$this->partial("module/folder/partial.phtml", array(
"test" => "foo",
));
但是对对象
执行相同操作将不会导致部分结果:
$this->partial("module/folder/partial.phtml", array(
"test" => $this,
));
我什至尝试过使用setObjectKey
,但也没有醒来:
$this->partial()->setObjectKey("test");
$this->partial("module/folder/partial.phtml", $this);
有没有办法将对象
传递给ZF2中的单个部分?
我想这样做,因为我的 View 实际上包含了部分需要的许多信息。我可以将它们全部逐行添加到部分中,但这只是开销......
最佳答案
当您将父 Zend\View\Renderer\PhpRenderer
传递给您的部分时,它将用 Zend\View\覆盖/替换
,就像它正在重新使用该类一样。因此导致一个空对象,因为您的部分 $test
变量您的部分的 Renderer\PhpRendererPhpRenderer
不包含其他变量。
如果您想要来自父 PhpRender
的变量,请使用以下内容:
$this->partial('folder/partial', ['vars' => $this->vars()->getArrayCopy()]);
// Or so, so you don't need to store the originals within the vars key
$this->partial('folder/partial', $this->vars()->getArrayCopy());
现在在您的partial.phtml中:
$this->vars['foo']
要确认这一点,请让您的 Controller 返回一些变量 ['foo' => 'bar']
或使用一些测试变量设置 ViewModel
。现在设置你的部分:
$this->partial('folder/partial.phtml', ['test' => 'abc' 'render' => $this].
当您调试或 var_dump()
PhpRenders 变量时,您会看到 $render
包含带有值的变量 $test
abc 的键,而不是以“bar”作为其值的键“foo”。所以看起来 PhpRenderer 正在被重用,因此传递父 PhpRenderer
是不可能的。
关于php - 将对象传递给ZF2中的partial() View 助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41039016/