如何在不使用传递代码的情况下将View Helper变量传播到ZF2中的远程View子节点?

时间:2016-04-11 21:14:19

标签: php zend-framework2

我没有完整的ZF2堆栈,但是我操纵了大部分非ZF2代码来接受$this->partial()ViewModel()方法。

我经常发现我有一个View Helper Partials树的情况,其中一些远离根的孩子需要一个变量someVar

我管理该变量将它从每个partial从root传递给子节点,即使路由中的部分也不需要它。

有没有办法不用管理var?

示例

//controller.php
echo $this->partial('root.phtml', array('someVar' => $someVar));
//root.phtml
<? 
    //this variable-pass-through-only step is one I would like to eliminate.
    //aka. here someVar is not itself used in root.phtml
    //it is only passed onto the child view partial
    //I want to eliminate this pass-through-only code.

    echo $this->partial('child.phtml', array('someVar' => $this->someVar)):
?>
//child.phtml - leaf child
<?
    //variable is actually used for display purpose
    echo $this->someVar;
?>

我愿意接受使用非partial构造的答案,即ViewModel等。

注意:当我删除传递代码时,希望存在某种全局范围的变量,但事实并非如此 - 变量不会传递给子叶视图部分。我希望在ZF2中有一种更好的方法来实现我的目标。

问题的目标/精神

要明确我正在寻找一种方法来使一些变革成为一个全球性的#34; var,它从partial / view的根扩展到叶.phtml,没有传递代码,或者可能是一个完全不同的方法,我不需要这样做,但是不要使用传递变量使我的代码混乱

1 个答案:

答案 0 :(得分:2)

您可以使用嵌套的ViewModel实例来复制部分视图助手的功能。通过独立创建对象,无需将所有变量传递给每个对象。

一个简单的例子。

$main = new ViewModel(['var1' => 'xyz', 'var2' => 'xyz']);
$main->setTemplate('main.phtml');

$foo = new ViewModel(['baz' => 'bob']);
$foo->setTemplate('foo.phtml');

$bar = new ViewModel(['test' => 123]);
$bar->setTemplate('bar.phtml');

// foo.phtml should echo $this->barResultHtml
$foo->addChild($bar, 'barResultHtml');

// main.phtml should echo $this->fooResultHtml
$main->addChild($foo, 'fooResultHtml');

// You will need to set this up to render the view model.
$view = new Zend\View\View();
$view->setRenderer(...);

echo $view->render($main);
相关问题