What could cause a View template to ouput wrong row index? Context
I have a weird issue on my live environment that I have never seen on my local environment. Cache bins are disabled on my local environment and enabled on live server.
When clearing all caches on live server, the problem disappears for some time, then reappears. When disabling cache bins on live server the problem doesn't seem to happen anymore.
Issue
In my custom theme, I use a simple &quot;Single field&quot; template to override a given view field.
/**
 * @file
 * Theme override for a single field in a view.
 *
 * Available variables:
 * - view: The view that the field belongs to.
 * - field: The field handler that can process the input.
 * - row: The raw result of the database query that generated this field.
 * - output: The processed output that will normally be used.
 *
 * When fetching output from the row this construct should be used:
 * data = row[field.field_alias]
 *
 * The above will guarantee that you'll always get the correct data, regardless
 * of any changes in the aliasing that might happen if the view is modified.
 *
 * @see template_preprocess_views_view_field()
 */

In the output HTML of this field, I need a simple incremental id from 0 to n where n would be the total number of rows in the view results. Something like below for a View with 5 results:
&lt;div data-index=&quot;0&quot;&gt;...&lt;/div&gt;
&lt;div data-index=&quot;1&quot;&gt;...&lt;/div&gt;
&lt;div data-index=&quot;2&quot;&gt;...&lt;/div&gt;
&lt;div data-index=&quot;3&quot;&gt;...&lt;/div&gt;
&lt;div data-index=&quot;4&quot;&gt;...&lt;/div&gt;

So in my field template, I use:
&lt;div data-index=&quot;{{ row.index }}&quot;&gt;...&lt;/div&gt;

This works fine, except on some occasions, only on my live server with caching enabled where the output will be for example:
&lt;div data-index=&quot;0&quot;&gt;...&lt;/div&gt;
&lt;div data-index=&quot;1&quot;&gt;...&lt;/div&gt;
&lt;div data-index=&quot;19&quot;&gt;...&lt;/div&gt;
&lt;div data-index=&quot;3&quot;&gt;...&lt;/div&gt;
&lt;div data-index=&quot;21&quot;&gt;...&lt;/div&gt;

Important notes:

I sometimes get indices such as 19 when there are only 10 or 15 results in the view so that number seems to come out of the blue.
This happens when the view is filtered using a single taxonomy term.

Question
Am I wrong assuming that row.index should give me an incremental sequence of integers for every view, with or without caching? If I am wrong, then what should I be using? And if not, what could cause this behavior?
To solve it using views-view-field.html.twig
First in view settings, add field &quot;View Result Counter&quot; and hide from display.
Now in your twig you can do
&lt;div data-index=&quot;{{ view.field['counter'].getValue(row) }}&quot;&gt;...&lt;/div&gt;