使用响应对象渲染视图

Posted

技术标签:

【中文标题】使用响应对象渲染视图【英文标题】:Render view using response object 【发布时间】:2018-08-06 06:40:58 【问题描述】:

我正在 symfony 3 中开发一个项目,我有以下代码返回一个响应实例

public function dashboardAction()

    return parent::dashboardAction();

以上代码的父方法是:

public function dashboardAction()

    $blocks = [
        'top' => [],
        'left' => [],
        'center' => [],
        'right' => [],
        'bottom' => [],
    ];

    foreach ($this->container->getParameter('sonata.admin.configuration.dashboard_blocks') as $block) 
        $blocks[$block['position']][] = $block;
    

    $parameters = [
        'base_template' => $this->getBaseTemplate(),
        'admin_pool' => $this->container->get('sonata.admin.pool'),
        'blocks' => $blocks,
    ];

    if (!$this->getCurrentRequest()->isXmlHttpRequest()) 
        $parameters['breadcrumbs_builder'] = $this->get('sonata.admin.breadcrumbs_builder');
    

    return $this->render($this->getAdminPool()->getTemplate('dashboard'), $parameters);

我想将变量articles 传递给响应实例中的视图。

我试着做这样的事情

return $this->render(parent::dashboardAction(), array(
        'articles' => $articles,
    ));

但它不起作用。有什么帮助吗?

【问题讨论】:

【参考方案1】:

$this->render 返回一个 Response 对象,第一个参数是要渲染的模板的名称(一个字符串)。您试图再次将 Response 对象作为第一个参数传递给 render,这显然行不通。

同样$this->render 会使用提供的参数逐字呈现模板。这意味着您的父dashboardAction 的返回值返回一个响应对象,其中包含$this->getAdminPool()->getTemplate('dashboard') 返回的模板的呈现html。如果您不想实际使用完全渲染的 HTML(不,您不想这样做),那么此时您无法更改渲染的 HTML。

总的来说,我认为直接重用操作方法不是一个好主意。相反,您可以执行以下操作:

在你的父类中创建一个方法getDashboardParameters,它只返回render函数的参数,不调用render

protected function getDashboardParameters()

    $blocks = [
        'top' => [],
        'left' => [],
        'center' => [],
        'right' => [],
        'bottom' => [],
    ];

    foreach ($this->container->getParameter('sonata.admin.configuration.dashboard_blocks') as $block) 
        $blocks[$block['position']][] = $block;
    

    $parameters = [
        'base_template' => $this->getBaseTemplate(),
        'admin_pool' => $this->container->get('sonata.admin.pool'),
        'blocks' => $blocks,
    ];

    if (!$this->getCurrentRequest()->isXmlHttpRequest()) 
        $parameters['breadcrumbs_builder'] = $this->get('sonata.admin.breadcrumbs_builder');
    

    return $parameters;

将您的父仪表板操作更改为如下所示:

public function dashboardAction() 
    return $this->render($this->getAdminPool()->getTemplate('dashboard'), $this->getDashboardParameters());

将您的子仪表板操作更改为如下所示:

public function dashboardAction() 
    $parameters = $this->getDashboardParameters();
    $parameters['articles'] = $articles;
    return $this->render($this->getAdminPool()->getTemplate('dashboard'), $parameters);

【讨论】:

以上是关于使用响应对象渲染视图的主要内容,如果未能解决你的问题,请参考以下文章

django框架--视图系统

视图 模板渲染 过滤器(内置) 标签

Vue响应式原理obserserver、Dep、Watcher 的作用

是否可以一次通过多个视图渲染对象

错误渲染视图:java.lang.IllegalStateException:已为此响应调用了getOutputStream()

如何通过主干中的 ajax 调用使用模型渲染多个视图