[英]Symfony how to include controller on base.html.twig
I have a small question, I'm new to symfony, I created a controller and a menu template that I want to integrate into my base.html.twig.
我绝对需要调用 controller 因为我正在测试知道 session 变量是否为空。
{% block menu %}
{% include 'menu/index.html.twig' %}
{% endblock %}
<body>
{% block body %}{% endblock %}
</body>
所以我尝试了这个(它工作得很好,但它没有调用我的 controller 所以当我在 session 上进行测试时它不会工作......)
我搜索了,但我不能包含 controller 而不是模板...
提前致谢
不应从 twig 调用 controller。 EOT
您需要将代码从 controller 移动到服务或帮助程序。 然后你应该从 controller 运行服务。
此外,您需要创建一个新的 twig function 并在此 function 中调用服务/帮助程序代码。
这样,代码形式 controller 将以正确的方式在 twig 中执行。
In Symfony, you cannot call a Controller from inside a twig, what you can do is store variables inside a Controller, and then call those variables from inside the twig.
例如,在您的情况下,在 Controller 中,您创建变量并将其保存在 session 中,如下所示:
//...
class BaseController extends AbstractController
{
//...
$session->set('var_i_need', 222);
return $this->render('menu/index.html.twig', [
'controller_name' => 'BaseController',
]);
}
然后在 twig 里面你得到变量:
{% set var_i_need = app.session.get('var_i_need') %}
并测试它是否为空:
{% if var_i_need is not NULL %}
{% ... %}
{% endif %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.