1

是否可以将数组中的多个视图添加到 Zend Framework 2 中的父视图?例如:

子视图.php

echo $this->data;

父视图.php:

foreach($this->views as $view)
    echo '<div>'.$view.'</div>';

控制器.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:这是虚拟代码,所以请忽略可能的语法错误。

4

3 回答 3

3

您可以将 ViewModel 数组分配给您的父 View Model。

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

现在你可以在你的父模板中迭代它们:

父视图.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 ?>
于 2013-05-14T12:36:04.607 回答
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);

将子视图附加到这个变量。因此,您可以使用以下方法回应您的观点:

<?php echo $this->the-child-views ?>

希望这是您正在寻找的。

于 2013-05-15T09:04:36.617 回答
-1

我认为它应该与部分助手一起使用:http: //framework.zend.com/manual/2.1/en/modules/zend.view.helpers.html#partial-helper

于 2013-05-14T10:30:15.960 回答