php Symfony2 - Twig - 如何将参数发送到父模板?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17244162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Symfony2 - Twig - How can I send parameters to the parent template?
提问by Germán Lena
I am working on a PHP project using Symfony2 with Twig templating, and I can't find a solution for this problem.
我正在使用带有 Twig 模板的 Symfony2 处理 PHP 项目,但我找不到解决此问题的方法。
I have an admin bundle and all the templates extend from admin base which has a master template with a menu.
我有一个管理包,所有模板都从管理库扩展,管理库有一个带菜单的主模板。
I need to set the current tab of the menu in the base template of the page to selected when the user is on that page.
当用户在该页面上时,我需要将页面基本模板中菜单的当前选项卡设置为选中。
Is there any way to pass parameter to the base template through extends?
有没有办法通过extends将参数传递给基本模板?
回答by Paul
Here is a simple example:
这是一个简单的例子:
base.html.twig:
base.html.twig:
{# base.html.twig #}
...
<ul>
<li{% if menu_selected|default('one') == 'one' %} class="selected"{% endif %}>One</li>
<li{% if menu_selected == 'two' %} class="selected"{% endif %}>Two</li>
<li{% if menu_selected == 'three' %} class="selected"{% endif %}>Three</li>
</ul>
...
page2.html.twig:
page2.html.twig:
{# page2.html.twig #}
{% extends 'YourBundle::base.html.twig' %}
{% set menu_selected = 'two' %}
Output from rendering page2.html.twig:
渲染 page2.html.twig 的输出:
<ul>
<li>One</li>
<li class="selected">Two</li>
<li>Three</li>
</ul>
回答by pogeybait
A better way that I just discovered is the basic approach by checking the route for the shortcut route name:
我刚刚发现的一个更好的方法是通过检查快捷路线名称的路线的基本方法:
<li class="{% if app.request.attributes.get('_route') == 'homepage' %}active{% endif %}">Home</li>
Or another way is to name all your route shortcut names according to the group it belongs to. For example all the routes from your products controller start with "product_...." and then in the template you can do this:
或者另一种方法是根据其所属的组命名所有路线快捷方式名称。例如,您的产品控制器中的所有路由都以“product_....”开头,然后在模板中您可以执行以下操作:
<li class="{% if app.request.attributes.get('_route') starts with 'product' %}active{% endif %}">