How to increment variable in Twig file? I'm using a view grid template and a views-view-fields--view-machine-name.html.twig template file in order to render some pictures in grid format. I want to assign dynamic CSS classes to every picture that is being rendered, for example, using the following markup.

&lt;div class="profile-pic pic{{id}}"&gt;{{ fields.field_picture.content }}&lt;/div&gt;


I have set a variable in Twig with the following code, but since there is no loop, it doesn't get incremented.

{% set id = 0 %}


So for every picture I have the same CSS classes (profile-pic pic0).

I want to get the following.


Picture 1
profile-pic pic0 
Picture 2
profile-pic pic1 
Picture 3
profile-pic pic2 
Picture 4
profile-pic pic3 


If I use the following code, the same imagine is rendered instead of the pictures I have.

{% for field in fields -%}
  &lt;div class="profile-pic pic{{id}}"&gt;{{ fields.field_picture.content }}&lt;/div&gt;
{%- endfor %}


How do I get the counter to be increased, and all the images to be rendered?
As you mentioned, there's no loop, so you can't do this in the template file (well you could, but it wouldn't be worth the effort).

Instead, you could maintain a static variable in a preprocess function:

function MYTHEME_preprocess_views_view_fields__view_machine_name(&amp;$vars) {
  static $counter = 0;
  $vars['counter'] = $counter++;
}


And refer to it in the template as normal:

&lt;div class="profile-pic pic{{ counter }}"&gt;{{ fields.field_picture.content }}&lt;/div&gt;


You might need to tweak that, for example if the View is rendered twice on the same page.