Symfony2 - Twig渲染控制器并返回数组响应

Jim*_*mbo 5 php symfony twig

注意:我在这里做的是嵌入控制器 <---请参阅类似(官方)示例的链接.

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

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

枝条

{% set testVar = render(controller('AppBundle:Test:index')) %}
Run Code Online (Sandbox Code Playgroud)

调节器

class TestController extends Controller
{
    public function testAction()
    {
        return new Response('OH HAI');
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,以下引发异常:("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'));
}
Run Code Online (Sandbox Code Playgroud)

这引发了上述异常.如何在不创建虚拟的,无用的额外模板的情况下完成我所寻求的控制器渲染

Cyp*_*ian 5

实现你想要的东西的标准方式看起来像那样.

让我们假设你有规律的行动.例如.

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

和模板:

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

接下来,您需要为侧边栏创建一些操作.请注意,这样可以避免将任何逻辑放入视图层.

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,
        ));
    }
}
Run Code Online (Sandbox Code Playgroud)

你的Base/sidebar.html.twig:

<div class="sidebar">
   {{ status.showStatusInfo() }}
</div>
Run Code Online (Sandbox Code Playgroud)

就这样.你不是以这种方式打破MVP,因为你的视图层中仍然没有任何逻辑(侧边栏的逻辑在里面BaseController).