reformed
reformed

Reputation: 4808

How to loop over sequence with variable in Twig?

According to Twig's documentation on the "for" tag, the .. operator can be used to iterate over a sequence of numbers:

{% for i in 0..10 %}
    * {{ i }}
{% endfor %}

Is it possible to use a variable that stores the upper bound, instead of a hard-coded number? e.g.,

{% set max = 10 %}
...
{% for i in 0..{{ max }} %}
    * {{ i }}
{% endfor %}

When I try the above code, I get this error:

A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{".

Upvotes: 2

Views: 638

Answers (1)

Teneff
Teneff

Reputation: 32148

You should be able to use the variable like this

{% set max = 10 %}
...
{% for i in 0..max %}
    * {{ i }}
{% endfor %}

playground example

Upvotes: 2

Related Questions