Mojtaba Reyhani
Mojtaba Reyhani

Reputation: 457

How can I use loop functionality in twig template?

I want to use a looping functionality in region.html.twig file to I can wrap elements that outputted from {{ content }} section.

Defult region.html.twig

{% if content %}
  <div class="Parent">
    {{ content }}
  </div>
{% endif %}

The schematic generated Output:

<div class="Parent">
  Item_1
  Item_2
  Item_3
</div>

I try to use below code to create a loop and add a wrapper around of each Item outputted from {{ content }}:

My code:

{% if content %}
  <div class="Parent"> 
    {% for item in items %}
      <div class="child-wrapper">{{ item.content }}</div>
    {% endfor %}
  </div>
{% endif %}

The Final outpute that I want to achive:

<div class="Parent">
  <div class="child-wrapper">Item_1</div>
  <div class="child-wrapper">Item_2</div>
  <div class="child-wrapper">Item_3</div>
</div>

Upvotes: 0

Views: 800

Answers (1)

Skribja
Skribja

Reputation: 161

If your data is: content = [1, 2, 3, ... , 100]

   Then write
    {% if content %}
      <div class="Parent"> 
        {% for item in content %}
          <div class="child-wrapper">{{ item }}</div>
        {% endfor %}
      </div>
    {% endif %}

If your data is array of assotiated arrays like this: 
content = [
    ['content' => 1],   
    ['content' => 2],   
]

   Then write
    {% if content %}
      <div class="Parent"> 
        {% for item in content %}
          <div class="child-wrapper">{{ item.content }}</div>
        {% endfor %}
      </div>
    {% endif %}

Upvotes: 1

Related Questions