简体   繁体   中英

Passing variable into included twig template that has variable in template name

Is it possible to pass variables into an included twig template, where the template name is a variable in itself?

{% include('MyMainBundle:MyEntity:' ~ entity.templateName) %}

works, but when I try to also pass a variable into this template, twig throws a syntax error.

{% include('MyMainBundle:MyEntity:' ~ entity.templateName, {'name' : myName} ) %}

I see what I was doing wrong. I had combined two different versions of include, one using {{ and the other using {% due to the symfony and twig docs showing different ways of including templates. This was as simple as removing the parenthesis from my initial code and inserting a with prior to defining the argument.

You can include a template like this per http://symfony.com/doc/current/book/templating.html#including-other-templates

{{ include('AcmeArticleBundle:Article:articleDetails.html.twig', {'article': article}) }}

Or like this per http://twig.sensiolabs.org/doc/tags/include.html

{% include 'template.html' with {'foo': 'bar'} %}

For a template name as a variable, I had to use this format:

{% include 'AcmeCalendarBundle:Default:cal_event_' ~ day.item.type ~ '.html.twig' with {'item': day.item} %}

Using

{{ include 'AcmeCalendarBundle:Default:cal_event_' ~ day.item.type ~ '.html.twig', {'item': day.item} }}

did not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM