我必须用一个宏设置一个变量,它返回一个数字,所以我有这个宏:
{% 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 %}
有了这个,我用宏成功设置了变量。
我的问题:这是一种不好的做法,是否有更好的方法来设置变量?
谢谢!