When using a grouping field in an HTML list, is there a way to determine the group/loop number of the current content being rendered?

drupal.stackexchange https://drupal.stackexchange.com/questions/300117

  •  02-03-2021
  •  | 
  •  

Question

I want to be able to determine what group number is currently being processed to that I can treat the output of the first group differently than subsequent groups.

Unlike rows, I do not see a way to find the current count of groups or loops through the view such that I could, for instance, do something like the following (i.e., classing group content by group iteration) -

<div class="item-list">
  <h3 class="group-1">{{ title }}</h3>
  <ul class="group-1">
    {% for row in rows %}
      <li{{ row.attributes }}>
        {{- row.content -}}
      </li>
    {% endfor %}
  </ul>
</div>
<div class="item-list">
  <h3 class="group-2">{{ title }}</h3>
  <ul class="group-2">
    {% for row in rows %}
      <li{{ row.attributes }}>
        {{- row.content -}}
      </li>
    {% endfor %}
  </ul>
</div>
...
<div class="item-list">
  <h3 class="group-n">{{ title }}</h3>
  <ul class="group-n">
    {% for row in rows %}
      <li{{ row.attributes }}>
        {{- row.content -}}
      </li>
    {% endfor %}
  </ul>
</div>
Was it helpful?

Solution

I don't know of a way to get the group number from within the grouping (e.g. views-view-list) template, but I would look to do this split between two templates: views-view and views-view-list.

First, in the views-view template, e.g. views-view--my-view-id.html.twig.

{# ... etc ... #}
{# Loop through the rows, aka groups, and add a wrapper with index identifier. #} 
{% for row in rows %}
  <div class="item-list group--{{ loop.index }}">
    {{ row }}
  </div>
{% endfor %}
{# ... etc ... #}

Second, create your views-view-list template, e.g. views-view--my-view-id.html.twig to build the content for each group:

<h3>{{ title }}</h3>
<ul>
  {% for row in rows %}
  <li{{ row.attributes }}>
      {{- row.content -}}
    </li>
  {% endfor %}
</ul>

Then you can target the contents of each group in css like:

.group--1 h3 { }
.group--1 ul { }
.group--2 h3 { }
.group--2 ul { }
.etc { }
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top