6

I worked briefly with Drupal 7 and I thought it was possible there but in Drupal 8 is it possible to have a view output an increasing numbered CSS classes for Views rows?

This is what I want.

<div class="view">
  <div class="view-row-1"></div>
  <div class="view-row-2"></div>
  <div class="view-row-3"></div>
  <div class="view-row-4"></div>
</div>

I know I can add a CSS class to every row and give every row the same class.

11

In Drupal 7 and 8 the add view row classes is check-marked by default.

enter image description here

The problem is that in Drupal 8, it does not work. (looks like this is a bug)

enter image description here

As you can see in the above picture, the number is missing on the div class.

Luckily, there is a workaround solution.

In FIELDS, add Global: View result counter and hide it from display

In FORMAT, click on Settings (the 1st one)

For row class, put for example: hello-{{ counter }} and uncheck-mark "add view row class", as you don't need it.

enter image description here

Result

enter image description here

| improve this answer | |
5

I liked the solution provided by @No Sssweat

As the above solution still an issue in https://www.drupal.org/node/2669394.

Other way is Rewrite results where you can add the classes like you need.

Add Global: View result counter and hide it from display

<div class="views-row-{{ counter }}">
</div>
| improve this answer | |
2

You can also do this in your views-view--[view name].html.twig template by replacing

{{ rows }}

with

{% set totalrows = rows[0]['#rows']|length %}
{% for row in rows[0]['#rows'] %}
     {% set rownum = ( rownum | default(0) ) + 1 %}
     <p>This is row: {{ rownum }} of {{ totalrows }}</p>
     {{ row }}
{% endfor %}
| improve this answer | |
2

Or you can use the module Semantic Views to number row classes, first/last and every nth row, custom markup and more.

This Views plugin makes unformatted styles, field row styles and other output more readily configurable without needing to override template files. Instead of overriding row style templates for views where you want to specify different HTML elements (tags) and class attributes, you can specify these inside the Views UI and avoid overriding templates for each view.

| improve this answer | |
0

For me the easiest way to print numbered CSS classes in Views rows was per the following Twig snippet.

{% for key, row in rows %}
  <div class="view-row-{{ key+1 }}">
    {{ row }}
  </div>
{% endfor %}

This will output the following markup.

<div class="view-row-1"></div>
<div class="view-row-2"></div>
<div class="view-row-3"></div>
<div class="view-row-4"></div>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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