我必须用宏来设置一个变量,它返回一个数字,所以我有这个宏:
{% 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 %}
有了这个,我用一个宏成功设置了变量。
我的问题:这是一个不好的做法,有更好的方法来设置变量吗?
谢谢!
答案 0 :(得分:0)
在我看来,为树枝设置变量的两种方法都很好。 1.使用主题和其他钩子(内部主题或任何模块)并从php传递变量, 2.创建枝条扩展/过滤器
示例:
过滤器: http://leopathu.com/content/create-custom-twig-filter-drupal-8
扩展:
http://symfony.com/doc/current/templating/twig_extension.html