Drupal - How to increment variable in Twig file?

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(&$vars) {
  static $counter = 0;
  $vars['counter'] = $counter++;
}

And refer to it in the template as normal:

<div class="profile-pic pic{{ counter }}">{{ fields.field_picture.content }}</div>

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


You don't need another preprocess function anymore as you can easily do this in only Twig now. But you need another template. The one you are currently using loops through all fields of one row. Not just your image field. But you want to have the template that targets exactly this one image field, where you want to loop through all items of this field's .content.

For mere demonstration purpose I'll leave that untouched for now and only show you how to increment variables in a for-loop in Twig:

{% set id = 0 %}

{% for field in fields -%}
  <div class="profile-pic pic{{ id }}">{{ fields.field_picture.content }}</div>
  {% set id = id + 1 %}
{%- endfor %}

You might also wanna have a look at the loop variable where {{ loop.index }} or {{ loop.index0 }} simply gives you the current iteration of a loop. Two more lines saved.

{% for field in fields -%}
  <div class="profile-pic pic{{ loop.index0 }}">{{ fields.field_picture.content }}</div>
{%- endfor %}

And last but not least this little gem: slice – to display a subset of items. Let's say only the first five ones.

{% for field in fields|slice(0, 5) -%}
  <div class="profile-pic pic{{ loop.index0 }}">{{ fields.field_picture.content }}</div>
{%- endfor %}

Tags:

Views

Theming

8