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/