2015-10-07 80 views
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) %} 

注意:有了這個,你將設置與嫩枝標記變量。 (你可以看到,當你算賬調試變量)。

爲了得到一個數/整數價值,你必須把它轉換爲字符串(如果你用它計算將被解釋爲數字)

{% set image_size  = image_size.__toString %} 

有了這個,我使用宏成功設置了變量。

我的問題:這是一個不好的做法,有沒有更好的方法來設置變量?

謝謝!

+0

爲什麼不只是使用樹枝擴展而不是maccro? – pbenard

回答