将其他参数传递给Zend partialLoop View Helper

Cia*_*lty 13 php zend-framework

在Zend视图中,我可以将部分模板应用于可迭代元素,如下所示:

$this->partialLoop('template.phtml', $iterable);
Run Code Online (Sandbox Code Playgroud)

但是在模板中,只有$ iterable的元素可用,是否有另一种方法将额外的数据传递给部分?

Tom*_*far 13

我用

$this->partialLoop('template.phtml', array(
    'data' => $iterable, 
    'otherVariable' => $otherVariable
);
Run Code Online (Sandbox Code Playgroud)

警告和编辑:

说实话,我犯了一个错误.我想我提出的代码不起作用.我把它误认为是partial()助手.由于辅助类的这一部分,它不起作用:

foreach ($model as $item) {
    // increment the counter variable
    $this->partialCounter++;
    $content .= $this->partial($name, $module, $item);
}
Run Code Online (Sandbox Code Playgroud)

它将迭代整个数组而不是"数据"键.我不明白答案是如何被接受的:D感谢Nikolaus Dulgeridis指出这一点.

您甚至无法通过$ this-> view发布任何额外数据,因为部分点是它创建"干净"视图实例 - 因此分配的变量不会与您现有的变量发生冲突.

可能的选择

- 使用方法扩展视图助手以设置自定义变量

- 迭代数组并将其重新格式化为

array(
    array('data' => $item1, 'id' => 1, 'totalCount' => 10) ,
    array('data' => $item2, 'id' => 2, 'totalCount' => 10) ,
    array('data' => $item3, 'id' => 3, 'totalCount' => 10) ,
)
Run Code Online (Sandbox Code Playgroud)

- 使用Registry存储值.

Zend_Registry::set('partialLoopCount', $count);
$this->partialLoop($viewScript, $data);
Run Code Online (Sandbox Code Playgroud)

- 转储partialLoop并使用partial()代替

我更喜欢这个解决方案

$count = count($data);
foreach ($data as $key => $value) {
    echo $this->partial($viewScript, array('item' => $value, 'position' => $key, 'count' => $count));
}
Run Code Online (Sandbox Code Playgroud)


Bru*_*tti 13

在partial中,您可以使用以下命令访问所有视图变量:

$this->partialLoop()->view->myVariable
Run Code Online (Sandbox Code Playgroud)

其中myVariable是一个普通的视图变量($this->view->myVariable在控制器或 $this->myVariable视图中,它实际上是同一个东西).基本上,您检索PartialLoop()对象,然后检索调用它的视图,然后检索变量本身.

但是,这可能会影响性能(我认为它不是真正的MVC友好......)但是,嘿:它有效.:)

这里有一个例子: Hardcode.nl == Joris Osterhaus