是否可以将数组中的多个视图添加到Zend Framework 2中的父视图? 例如:
childView.php
echo $this->data;
parentView.php:
foreach($this->views as $view)
echo '<div>'.$view.'</div>';
Controller.php这样:
public function actionIndex(){
$children = array(1,2,3);
foreach($children as $child){
$childView = new ViewModel(array('data' => $child));
$childView->setTemplate('childView');
$childrenViews[] = $childView;
}
$view = new ViewModel();
$view->setTemplate('parentView');
// some function that adds the childrenViews to the parentView;
return $view;
}
预期输出:<div>1</div><div>2</div><div>3</div>
ps:这是虚拟代码所以请忽略可能的语法错误。
答案 0 :(得分:3)
您可以将ViewModel数组分配给父视图模型。
<?php
public function actionIndex()
{
$children = array(1,2,3);
foreach($children as $child){
$childView = new ViewModel(array('data' => $child));
$childView->setTemplate('childView');
$childrenViews[] = $childView;
}
$view = new ViewModel();
$view->setVariable('children', $children); // assign to $children
/**
* Or set in constructor
*/
//$view = new ViewModel(array(
// 'children' => $children
//));
$view->setTemplate('parentView');
return $view;
}
现在您可以在父模板中迭代它们:
parentView.phtml
<?php // $children or $this->children to access your array of ViewModels ?>
<?php foreach($children as $child): ?>
<?php echo $child // automatically rendered for you ?>
<?php endforeach ?>
答案 1 :(得分:3)
您可以执行以下操作:
public function actionIndex(){
$children = array(1,2,3);
foreach($children as $child){
$childView = new ViewModel(array('data' => $child));
$childView->setTemplate('childView');
$view->addChild($childView, 'the-child-views', true);
}
$view = new ViewModel();
$view->setTemplate('parentView');
return $view;
}
这一行:
$view->addChild($childView, 'the-child-views', true);
将子视图附加到此一个var。因此,您可以使用以下方式回显您的观点:
<?php echo $this->the-child-views ?>
希望这就是你要找的东西。
答案 2 :(得分:-1)