![](/img/trans.png)
[英]Create and set the value of a twig variable, using index.loop in the variable name
[英]Set a Variable with a Twig Macro
我必須用一個宏設置一個變量,該變量返回一個數字,所以我有這個宏:
{% 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 %}
這樣,我可以通過宏成功設置變量。
我的問題:這是不好的做法嗎,有沒有更好的方法來設置變量?
謝謝!
我認為,有兩種方法可以為細枝設置變量。 1.使用主題和其他掛鈎(在主題或任何模塊內部)並從php傳遞變量,2.創建樹枝擴展/過濾器
例子:
過濾器: http : //leopathu.com/content/create-custom-twig-filter-drupal-8
延期:
http://symfony.com/doc/current/templating/twig_extension.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.