Search code examples
javafor-loopjtwig

Java JTwig For Loop Using A Range Not Container


I want to be able to do the equivalent of the following loop using a JTwig template:

for (int i = 0; i < length; i++ ) { ... }

I have tried the following but neither seem to work:

{% set k = 10 %}
{% for i in 1..k %}
    <option value={{k}} >{{k}}</option>
{% endfor %}

Or

{% set k = 10 %}
{% for i in range(1,k) %}
    <option value={{k}} >{{k}}</option>
{% endfor %}

I can loop containers but can't seem to find a way of getting this kind of thing to work.


Solution

  • You have to add square brackets, like so:

    {% for i in [1..10] %}
        {{ i }}
    {% endfor %}
    

    I discovered this rather by accident. It seems to be missing from the documentation.