【问题标题】:Set a Variable with a Twig Macro使用 Twig 宏设置变量
【发布时间】:2015-10-07 10:04:49
【问题描述】:

我必须用一个宏设置一个变量,它返回一个数字,所以我有这个宏:

{% import _self as self %}

{% macro function_size(field) %}

  {% import _self as self %}

  {# initial Setup #}
  {% set field_length = 0 %}

  {# Field #}
  {% for key, value in field %}
    {% if not (key starts with "#") %}
      {% set field_length = field_length + 1 %}
    {% endif %}
  {% endfor %}

  {{ field_length }}

{% endmacro %}

宏循环遍历字段的条目并返回不以“#”开头的值的计数。

所以我用那个值设置了一个变量:

{% set image_size       = self.function_size(content.field_teaser_image) %}

注意:您将使用 Twig 标记设置变量。 (你可以在之后调试变量时看到。)

要获得一个数字/整数作为值,您必须将其转换为字符串(如果您使用它进行计算,它将被解释为一个数字)

{% set image_size       = image_size.__toString %}

有了这个,我用宏成功地设置了变量。

我的问题:这是一种不好的做法,有没有更好的方法来设置变量?

谢谢!

【问题讨论】:

  • 为什么不直接使用 twig 扩展而不是宏?

标签: drupal twig symfony drupal-8


【解决方案1】:

我认为有两种方法可以为 twig 设置变量。 1.使用主题和其他钩子(在主题或任何模块内)并从php传递变量, 2. 创建树枝扩展/过滤器

例子:

过滤器: http://leopathu.com/content/create-custom-twig-filter-drupal-8

扩展名:

http://symfony.com/doc/current/templating/twig_extension.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    相关资源
    最近更新 更多