简体   繁体   English

如何在twig的template_from_string中注入变量?

[英]How to inject variable inside template_from_string in twig?

I want to use template variable (as string) inside a loop.我想在循环中使用模板变量(作为字符串)。

{# Define my template #}
{% set my_template %}
    <span>{{ job.title }}</span>
    ...
{% endset %}

{# Using the template inside a loop #}
{% for job in jobs %}
    {{ include(template_from_string(my_template), { 'job', job }) }}
{% endfor %}

I expect it shows the template content with the corresponding value for "job", but there is an error: "Variable job is not defined"我希望它显示具有“作业”相应值的模板内容,但出现错误:“未定义变量作业”

use macro https://twig.symfony.com/doc/2.x/tags/macro.html 使用宏https://twig.symfony.com/doc/2.x/tags/macro.html

{% macro my_template(job) %}
    <span>{{ job.title }}</span>
    ...
{% endset %}

{# Using the template inside a loop #}
{% for job in jobs %}
    {{ include(template_from_string(_self.my_template(job)), { 'job', job }) }}
{% endfor %}

I think your include call has a mistake in passing the parameters. 我认为您的include调用在传递参数时出错。 You are providing a regular array instead of the hash (using the comma instead of the colon): 您提供的是常规数组而不是哈希(使用逗号而不是冒号):

{{ include(template_from_string(_self.my_template(job)), { 'job': job }) }}

Another option is to use the verbatim tag.另一种选择是使用verbatim标记。 This stops twig parsing the variables, and force string, so we can we run as twig template later on.这会停止 twig 解析变量并强制使用字符串,因此我们可以稍后作为 twig 模板运行。

Without verbatim :没有verbatim

{# Define my template #}
{% set jobs = ['11', '22'] %}
{% set job = 'outside' %}

{% set my_template %}
  <span>{{ job }}</span>
{% endset %}

{# Using the template inside a loop #}
{% for job in jobs %}
  {{ include(template_from_string(my_template), { 'job': job }) }}
{% endfor %

Output: outside outside (wrong)输出: outside outside (错误)

With verbatim :随着verbatim

{# Define my template #}
{% set jobs = ['11', '22'] %}
{% set job = 'outside' %}

{% set my_template %}
  {% verbatim  %}
    <span>{{ job }}</span>
  {% endverbatim %}
{% endset %}

{# Using the template inside a loop #}
{% for job in jobs %}
  {{ include(template_from_string(my_template), { 'job': job }) }}
{% endfor %

Output: 11 22 (correct)输出: 11 22 (正确)

Bonus - Drupal - no template_from_string() With verbatim :红利- Drupal的-没有template_from_string()随着verbatim

{# Define my template #}
{% set jobs = ['11', '22'] %}
{% set job = 'outside' %}

{% set my_template %}
  {% verbatim  %}
    <span>{{ job }}</span>
  {% endverbatim %}
{% endset %}

{# Using the template inside a loop #}
{% for job in jobs %}
  {{ {'#type': 'inline_template', '#template': my_template, '#context': {'job': job} } }}
{% endfor %

Output: 11 22 (correct)输出: 11 22 (正确)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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