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

时间:2009-11-04 10:38:10

标签: php zend-framework

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

$this->partialLoop('template.phtml', $iterable);

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

5 个答案:

答案 0 :(得分:13)

我用

$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->视图发布任何额外数据,因为部分原因是它创建了“干净”的视图实例 - 因此分配的变量不会与您现有的变量冲突。

可能的选项

- 使用设置自定义变量

的方法扩展视图助手

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

array(
    array('data' => $item1, 'id' => 1, 'totalCount' => 10) ,
    array('data' => $item2, 'id' => 2, 'totalCount' => 10) ,
    array('data' => $item3, 'id' => 3, 'totalCount' => 10) ,
)

- 使用Registry存储值。

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));
}

答案 1 :(得分:13)

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

$this->partialLoop()->view->myVariable

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

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

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

答案 2 :(得分:2)

后来我发现(部分插入):

$this->getHelper('PartialLoop')->view->otherVariable; 

答案 3 :(得分:1)

您可以通过以下方式访问父视图变量:

$this->ViewModel()->getCurrent()->getVariable('parentVariable');

找到http://blog.dossantos.com.au/how-to-access-parent-view-variables-from-a-partial-loop-in-zf2

答案 4 :(得分:0)

在控制器中

$this->view->otherVariable = 'otherVariable';

在“部分文件”中 - template.phtml

$this->otherVariable

(ZendFramework-1.11.4-最小)

相关问题