serviom
serviom

Reputation: 121

How create loop in twig template?

I want made loop like of this on twig template:

for($i=1;$i<100;$i++) {
 echo $i;
}

I solved this problem as:

{% if k > 0 %}
 {% for i in 0..k - 1 %}
      <div></div>
 {% endfor %}
{% endif %}

if k = 0 -> no loop
if k = 1 -> 1 loop
if k = 100 -> 100 lopp

May be is other solve?

Upvotes: 0

Views: 80

Answers (2)

DarkBee
DarkBee

Reputation: 15619

You can add the if inside the loop

{% for i in 0..k if k > 0 %}
 {{ i }}
{% endfor %}

demo


edit: This doesn't work anymore in twig 3.X. You have to place the if inside the codeblock

Upvotes: 1

alessio
alessio

Reputation: 189

You can use range to reproduce loop output similar to the first php example

{% for i in range(1, 100-1) %}
    {{ i }}
{% endfor %}

Upvotes: 2

Related Questions