Php ZF2-控制器中多个操作的同一视图文件

Php ZF2-控制器中多个操作的同一视图文件,php,zend-framework2,Php,Zend Framework2,我使用ZF2,我需要在添加和编辑操作中呈现相同的视图(html页面)。有没有办法在ZF2中执行此操作?在控制器中,您可以设置要渲染的视图脚本: function someAction() { $result = new ViewModel(); $result->setTemplate('somemodule/somecontroller/arbitraryscript'); return $result; } 如果要为所有操作设置一个模板,只需重写Constr

我使用ZF2,我需要在添加和编辑操作中呈现相同的视图(html页面)。有没有办法在ZF2中执行此操作?

在控制器中,您可以设置要渲染的视图脚本:

function someAction()
{
    $result = new ViewModel();
    $result->setTemplate('somemodule/somecontroller/arbitraryscript');

    return $result;
}

如果要为所有操作设置一个模板,只需重写Constructor方法:

<?php
namespace MyModel\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    /**
     * @var ViewModel
     * @access protected
     */
    protected $viewModel;

    public function __construct()
    {
        $this->viewModel = new ViewModel();
        $this->viewModel->setTemplate('MyModel/index/default.phtml');
    }

    public function indexAction()
    {
        $this->viewModel->setVariables(array(
            'message' => 'Hello indexAction()'
        ));
        return $this->viewModel;
    }

    public function otherAction()
    {
        return $this->viewModel->setVariables(array(
            'message' => 'Hello otherAction()'
        ));
    }
}

请记住返回ViewModel,以便前端可以捕捉它。在末尾添加“return$result;”。