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();
    – tostinni
    Sep 7, 2021 at 2:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.