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:

<td headers="view-title-table-column" class="views-field views-field-title" data-label="Title">
Title goes here

It's a fairly straightforward, two-step process:

  1. Add a template_preprocess_views_view_table() function to the theme, which provides a label string to the theme layer.
  2. Add a 'views-view-table.html.twig' template to the theme and add the attribute to the cell.


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.

function MYmodule_preprocess_views_view_table(&$variables) {
// Get view id and display id from current view.
$view_id = $variables['view']->id();
$display_object = $variables['view']->getDisplay();
$display_id = $display_object->display['id'];

// Check for view id and display id.
if ($view_id == 'example_view' && $display_id == 'page_1') {
    foreach (
$variables['rows'] as $row_id => $row) {
      foreach (
$row['columns'] as $column_id => $column) {
$variables['rows'][$row_id]['columns'][$column_id]['label'] = $variables['header'][$column_id]['content'];


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:

<td{{ column.attributes.addClass(column_classes).setAttribute('data-label', column.label) }}>

The setAttribute method is defined as

attributes.setAttribute($attribute, $value)

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