php - Symfony2 - Twig 渲染 Controller 和返回数组响应

标签 php symfony twig

Note: What I'm doing here is embedding controllers <--- see that link for a similar (official) example.

我想从一个 twig 模板调用一个 Controller ,并让该 Controller 返回一个数组,然后我可以在我的模板的其余部分使用它。

我可以用单个变量来做到这一点:

Twig

{% set testVar = render(controller('AppBundle:Test:index')) %}

Controller

class TestController extends Controller
{
    public function testAction()
    {
        return new Response('OH HAI');
    }
}

但是,以下抛出异常:("The Response content must be a string or object implementing __toString(), "array"given.") 具有相同的 Twig 文件.

public function testAction()
{
    return new Response(array('test' => 1, 'foo' => 'bar'));
}

这会引发上述异常。我如何才能完成我寻求的目标,而不是为 Controller 创建一个虚拟的、无用的额外模板来呈现?

最佳答案

实现您想要的目标的标准方法看起来像那样。

让我们假设您有常规操作。例如。

class TestController extends Controller
{
    public function testAction()
    {
        return $this->render('AppBundle:Test:index.html.twig');
    }
}

和模板:

<html>
    <body>
        {% block sidebar %}
            {{ controller('AppBundle:Test:sidebar') }}
        {% endblock %}
        {% block content %}
            Hello world
        {% endblock %}                    
    </body>
</html>

接下来您需要为侧边栏创建一些 Action 。请注意,通过这种方式,您可以避免将任何逻辑放入 View 层。

class BaseController extends Controller
{
    public function sidebarAction()
    {
        $status = $this->get('some.status.logic')->retrieveStatus();

        return $this->render('AppBundle:Base:sidebar.html.twig', array(
            'status' => $status,
        ));
    }
}

还有你的Base/sidebar.html.twig:

<div class="sidebar">
   {{ status.showStatusInfo() }}
</div>

仅此而已。您并没有以这种方式破坏 MVP,因为您的 View 层中仍然没有任何逻辑(侧边栏的逻辑在 BaseController 中)。

关于php - Symfony2 - Twig 渲染 Controller 和返回数组响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16918738/

相关文章:

php - Symfony2 防火墙需要很长时间

Phpdocumentor 在供应商目录中查找自定义模板

mysql - Doctrine 迁移中的错误

php - 如何在 JS 中存储 PHP 变量以便与 jQuery 一起使用?

php - 用 PHP 改变 CSS

php - 如何使用$_GET或$_POST变量来区分每种类型的请求?

php - 部署者 : Deploy from local machine without repository

symfony - 渲染过程中抛出异常?

php - 如何将变量从父模板传递到 Twig 中的子模板?

php - PHP 中类采样的漏洞