将变量传递到包含模板名称中具有变量的twig模板中

RHa*_*ton 19 symfony twig

是否可以将变量传递到包含的树枝模板中,模板名称本身就是变量?

{% include('MyMainBundle:MyEntity:' ~ entity.templateName) %}
Run Code Online (Sandbox Code Playgroud)

工作,但当我尝试将变量传递到此模板时,twig会引发语法错误.

{% include('MyMainBundle:MyEntity:' ~ entity.templateName, {'name' : myName} ) %}
Run Code Online (Sandbox Code Playgroud)

RHa*_*ton 41

我明白我做错了什么.我结合了两个不同版本的include,一个使用{{和另一个使用{%,因为symfony和twig文档显示了包含模板的不同方式.这就像从我的初始代码中删除括号并在定义参数之前插入with一样简单.

您可以根据http://symfony.com/doc/current/book/templating.html#including-other-templates包含这样的模板

{{ include('AcmeArticleBundle:Article:articleDetails.html.twig', {'article': article}) }}
Run Code Online (Sandbox Code Playgroud)

或者像这样http://twig.sensiolabs.org/doc/tags/include.html

{% include 'template.html' with {'foo': 'bar'} %}
Run Code Online (Sandbox Code Playgroud)

  • 一旦StackOverflow允许我......我会明天解决它吗?好吗? (3认同)

pus*_*sle 6

对于模板名称作为变量,我必须使用以下格式:

{% include 'AcmeCalendarBundle:Default:cal_event_' ~ day.item.type ~ '.html.twig' with {'item': day.item} %}
Run Code Online (Sandbox Code Playgroud)

运用

{{ include 'AcmeCalendarBundle:Default:cal_event_' ~ day.item.type ~ '.html.twig', {'item': day.item} }}
Run Code Online (Sandbox Code Playgroud)

不工作.