Angel
Angel

Reputation: 1009

Use line break inside of a for loop in twig using Symfony 4

Trying to study the conditional statement. In here I want to indicate if it is even or odd and I want to put some line break after the other.

Example

1 - Odd

2 - Even

Question: Where should I put the |nl2br?

NOTE: I tried this {{ i ~ " " ~ cycle(['even', 'odd'], i)|nl2br }} and it didnt work.

My twig

{# For loop even and odd #}

    {% for i in 1..10 %}
    {{ i ~ " " ~ cycle(['even', 'odd'], i) }}

    {% endfor %} 

Upvotes: 1

Views: 1614

Answers (2)

Matteo
Matteo

Reputation: 39470

The nl2br:

The nl2br filter inserts HTML line breaks before all newlines in a string...

So you should insert a \n in your example in order to make the filter works. You can also use the odd or even test, as example:

{% for i in 1..10 %}
{{ (i ~ " " ~ ( i is odd ? "odd" : "even")~ "\n")|nl2br  }}
{% endfor %}     

Hope this help

Upvotes: 1

ryantdecker
ryantdecker

Reputation: 1810

Don't forget twig is extending HTML - you can just put the HTML you want right in place, as long as it's not inside the {{ }}

{% for i in 1..10 %}
  {{ i ~ " " ~ cycle(['even', 'odd'], i) }}<br/>
{% endfor %} 

Though, depending on your purpose, you might want to actually wrap the item in an HTML element:

{% for i in 1..10 %}
  <p>{{ i ~ " " ~ cycle(['even', 'odd'], i) }}</p>
{% endfor %} 

Upvotes: 4

Related Questions