Home > other >  get first item in loop with .twig
get first item in loop with .twig

Time:02-10

I am looping through an array and would like to add a class if it is the first item.

I have tried

{% if field|first %}
{% if field.first %}
{% if field.first() %}
{% if loop|first %}
{% if loop.first %}
{% if loop.first() %}

none work, please help. (the reason I don't use css pseudo first is that this is a grid layout and I have am doing responsive layout things with it)

   {% for field in row.fields %}    
       <div >  
          <span >{{ field.text }}</span>   
       </div>
   {% endfor %} 

I don't know why twig filters are not working, I solved it another way. I set a var and made it blank after first loop

  {% set thiscount = 'first_item' %}
  {% for field in row.fields %} 
    <div > 
      <span >{{ field.text }}</span>   
     </div>
  {% set thiscount = '' %}
  {% endfor %}  

CodePudding user response:

  •  Tags:  
  • Related