1

In a views template (views-view-unformatted.twig.html), I have

{% for row in rows %} {% set row_index = loop.index0 %} {{ row.content }} {% endfor %} 

where each row is processed in a node--view.twig.html. How can I pass in row_index to the node--view.twig.html? This is used simply to create an index.

1 Answer 1

2

This can be done using the preprocess function in my_theme.theme. In the case above, the row was formatted in node--view--pagename.html.twig, so the preprocessor function name is mytheme_preprocess_node__view__pagename. In the function, the view is iterated until the node matches the current node that is being processed, at that point, the row_index is determined and set and accessible in node--view--pagename.html.twig as {{ row_index }}.

function fu_preprocess_node__view__pagename(&$vars) { $view = $vars['view']; $node = $vars['node']; foreach($view->result as $key => $row){ if($row->nid == $node->id()){ $vars['row_index'] = $row->index; } } } 
1
  • This is great, thanks for sharing. A small thing however, $vars['view'] isn't available so you should try $view = views_get_current_view(); Commented Sep 7, 2021 at 2:11

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.