如何在树枝中的 template_from_string 内注入变量?

How to inject variable inside template_from_string in twig?

我想在循环中使用模板变量(作为字符串)。

{# 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 %}

我希望它显示具有 "job" 对应值的模板内容,但出现错误:"Variable job is not defined"

使用宏 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 %}

我认为您的 include 调用在传递参数时出错。您提供的是常规数组而不是散列(使用逗号而不是冒号):

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

另一种选择是使用 verbatim 标签。 这会停止 twig 解析变量,并强制字符串,所以我们可以 运行 稍后作为 twig 模板。

没有 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 %

输出:outside outside(错误)

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 %

输出:11 22(正确)

奖金 - Drupal - 无 template_from_string() With 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 %

输出:11 22(正确)