2

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

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

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

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

谢谢!

4

1 回答 1

0

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

例子:

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

扩大:

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

于 2016-12-29T09:54:30.807 回答