views – Using hook_preprocess_views_view_unformatted properly


I have the following hook in mymodule.module

function mymodule_preprocess_views_view_unformatted(&$variables) {
  $view = $variables('view');
  $rows = $variables('rows');

  if (in_array($view->id(),
      (
        'my_view',
      )
    )
  )
    {
        foreach ($rows as $id => $row) {
          $custom_row_class = 'card-background-' . get_card_background();
          var_dump($custom_row_class);
          $variables('rows')($id)('attributes')->addClass(($custom_row_class));
        }

      var_dump($variables('rows')(0)('attributes'));
    }
}

The output is:

/Users/me/Sites/mysite/web/modules/custom/mymodule/mymodule.module:55:string 'card-background-11' (length=18)

/Users/me/Sites/mysite/web/modules/custom/mymodule/mymodule.module:58:
object(DrupalCoreTemplateAttribute)(7400)
  protected 'storage' => 
    array (size=1)
      'class' => 
        object(DrupalCoreTemplateAttributeArray)(7223)
          protected 'value' => 
            array (size=1)
              ...
          protected 'name' => string 'class' (length=5)

Right after supposedly adding the class to the rows attributes, it isn’t there, and not surprisingly isn’t in the attributes value passed to views-view-unformatted.html.twig.