Add Attributes to Table Markup in Views
Recently, I ran into a use case where I needed to add attributes to table cells generated by Views in Drupal 8. Specifically, I needed to add a 'data-' attribute to facilitate responsive theming, so the end result would be something like this:
It's a fairly straightforward, two-step process:
- Add a template_preprocess_views_view_table() function to the theme, which provides a label string to the theme layer.
- Add a 'views-view-table.html.twig' template to the theme and add the attribute to the cell.
template_preprocess_views_view_table()
First, we'll add a template_preprocess_views_view_table function to the theme's .theme file. Unless, we check the view's id and display id, any modifications will be applied to all tables generated by Views, so extract the these ids and check this is a view/display we want to modify. Then we loop through all of the rows and columns and add the field's label to the each, individual column definition.
views-view-table.html.twig
Now that the label is available as part of the column array, we can add it as an attribute in Twig in views-view-table.html.twig:
The setAttribute method is defined as
Learn more at Using attributes in templates.
And that's it! Every <td> now has a 'data-label' attribute with the field's label.
Add new comment