Twig - 将参数传递给具有动态变量名称的函数

时间:2016-02-09 12:08:42

标签: symfony twig

我有Twig变量:

{{ totalAmountMonth5 }}

我有一个循环,我想调用这个变量,例如:

totalAmount.percentFromTotalAmount((totalAmountMonth5))

我想将此变量赋予这样的函数:

{% for i in 0..10 %}
    {{ totalAmount.percentFromTotalAmount(totalAmountMonth~i) }}
{% endfor %}

但这不起作用:

{% for i in 0..10 %}
    {{ totalAmount.percentFromTotalAmount('totalAmountMonth'~i) }}
{% endfor %}

这不起作用:

{{1}}

3 个答案:

答案 0 :(得分:2)

未经测试,但试试这个:

{% for i in 0..10 %}
  {{ totalAmount.percentFromTotalAmount(attribute(_context, 'totalAmountMonth'~i)) }}
{% endfor %}

答案 1 :(得分:2)

只需向你的树枝提供一个阵列,我建议或构建它(见下面的例子)

// use line below only if array isn't provided to twig
{% set totalAmounts = { totalAmount1, totalAmount2, ..., totalAmount10 } %} // pseudo-code; you need to declare all variables here
{% for ta in totalAmounts %}
    {{ totalAmount.percentFromTotalAmount(ta) }}
{% endfor %}

答案 2 :(得分:0)

尝试先设置该变量并使用它。

{% for i in 0..10 %}
   {% set temp = 'totalAmountMonth'~i %}
   {{ totalAmount.percentFromTotalAmount(temp) }}
{% endfor %}