在 Zend View 中,我可以将部分模板应用于可迭代元素,如下所示:
$this->partialLoop('template.phtml', $iterable);
然而在模板内部,只有 $iterable 的元素可用,是否有另一种方法将额外数据传递给部分?
最佳答案
我用
$this->partialLoop('template.phtml', array(
'data' => $iterable,
'otherVariable' => $otherVariable
);
警告和编辑:
老实说,我犯了一个错误。我想我提出的代码不会起作用。我把它误认为是 partial() 助手。由于助手类的这一部分,它不会工作:
foreach ($model as $item) {
// increment the counter variable
$this->partialCounter++;
$content .= $this->partial($name, $module, $item);
}
它将遍历整个数组而不是“数据”键。我不明白答案如何被接受 :D 感谢 Nikolaus Dulgeridis 指出这一点。
你甚至不能通过 $this->view 发布任何额外的数据,因为 partial 的要点是它创建了“干净”的 View 实例——这样分配的变量就不会与你现有的变量发生冲突。
可能的选择
- 使用设置自定义变量的方法扩展 View 助手
- 迭代数组并将其重新格式化为
array(
array('data' => $item1, 'id' => 1, 'totalCount' => 10) ,
array('data' => $item2, 'id' => 2, 'totalCount' => 10) ,
array('data' => $item3, 'id' => 3, 'totalCount' => 10) ,
)
- 使用注册表来存储值。
Zend_Registry::set('partialLoopCount', $count);
$this->partialLoop($viewScript, $data);
- 转储 partialLoop 并改用 partial()
我更喜欢这个解决方案。
$count = count($data);
foreach ($data as $key => $value) {
echo $this->partial($viewScript, array('item' => $value, 'position' => $key, 'count' => $count));
}
关于php - 将附加参数传递给 Zend partialLoop View Helper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1672976/