Views theme hook suggestions in Drupal 10

Recently, I stumbled upon a challenge while working on a Drupal 10 project. My task was to customize the appearance of views and their rows. The theme hook suggestions that I was so accustomed to using weren't appearing as they used to. It seemed like these helpful hints vanished after a recent Drupal update. 

Let's get into how you can get theme hook suggestions for a view and a views row in Drupal 10. The key lies in implementing hook_theme_suggestions_HOOK_alter(). Below, I've provided the code.

Here's how you can add theme hook suggestions for views:

/**
 * Implements hook_theme_suggestions_HOOK_alter() for views.
 *
 * Add views template suggestions.
 *
 * @inheritdoc
 */
function mytheme_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  // Add a suggestion for each view ID.
  $suggestions[] = 'views_view__' . $variables['view']->id();
}

And for views rows, particularly the unformatted ones, you can use the following code:

/**
 * Implements hook_theme_suggestions_HOOK_alter() for views unformatted rows.
 *
 * Add views unformatted row template suggestions.
 *
 * @inheritdoc
 */
function mytheme_theme_suggestions_views_view_unformatted_alter(array &$suggestions, array $variables) {
  // Add a suggestion for each view ID.
  $suggestions[] = 'views_view_unformatted__' . $variables['view']->id();
}

With these functions in your theme's .theme file, Drupal should start recognizing your template suggestions. These suggestions are dynamically generated based on the view ID, offering you a high degree of flexibility and control over your theme's presentation.

For my 'partners'-view I could now use:

  • views-view--partners.html.twig
  • views-view-unformatted--partners.html.twig

Cheers!

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!