How to dynamically add the view id as a body class for every views page

 

Here’s a quick guide to add custom CSS classes to the body tag of your page based on the views name for targeted styling of views pages.

Published on July 12, 2024

When building a lot of custom Drupal themes, you’ll notice you’re adding the same few enhancements with each new theme. For me, one of those is adding specific CSS classes to the <body> tag. More specifically, adding a class whenever a page is rendered by Views. 

In this quick tutorial, we'll explain how to add a dynamic CSS class in the format page-view-[view-id] to the <body> tag for pages rendered by Views. This will enable you to target these pages with unique styling.

Prerequisites

This write-up is intended for developers with a basic understanding of theming and PHP coding in Drupal. Before you begin, ensure you have a custom theme set up and that you're familiar with Drupal's theming system and hook usage.

Implementing the code

The method we use here relies on using the template_preprocess_html() hook in your custom theme. This hook allows you to alter the HTML variables before they are rendered. One of these variables is the classes array that is added to the body tag of each page rendered in your theme.

If the preprocess_html function is not yet in use, place the code in the following step in your theme's .theme file. This file should already be present in the root of your custom theme directory.

/**
 * Implements template_preprocess_html().
 */
use Drupal\Component\Utility\Html;

function MYTHEME_preprocess_html(&$variables) {
  // Add 'page-view-[view-id]' as body class
  $route = \Drupal::routeMatch()->getRouteObject();
  $view_id = $route->getDefault('view_id');
  // Clean the view title for use as css class
  $view_id_class = Html::cleanCssIdentifier($view_id);
  if ($view_id_class) {
    $variables['attributes']['class'][] = 'page-view-' . $view_id_class;
  }
}

Make sure to replace `MYTHEME` with your theme's machine name.

What is happening?

Here’s what's going on in the snippet you just added, line by line:

Getting the Route Object: We retrieve the current route object using Drupal's routing system.

Determining the View ID: Extract the view ID from the route defaults.

CSS Class Formation: Next we convert the view ID string to a valid CSS class. We use Html::cleanCssIdentifier() to convert any string of characters into a valid and safe to use CSS class, removing, replacing or encoding characters as necessary.

Add the class to the body tag: $variables['attributes']['class'][] - this line adds the new class to the array of CSS classes in the `<body>` tag. If there are any existing classes present, yours is added to the list.

Test your new feature

After adding the code, clear your Drupal site's cache. This step is essential as Drupal caches a lot of data, and your changes might not appear until the cache is cleared.

Navigate to any page rendered by a view in your Drupal site and inspect the <body> tag. You should see the new `page-view-[view-id]` class added to the class list. Use your browser's developer tools to confirm this.

Wrap-up

By adding dynamic CSS classes based on the view ID to your Drupal theme, you can target specific pages for unique styling with ease. This simple yet effective method allows you to manage the appearance of different views without having to add specific classes in the Views UI backend. This technique offers a straightforward way to target specific views pages with unique styling while keeping all code in the theming layer where it styling belongs.

Happy theming!


About the author

Thijs Boots (Drupal.org / Twitter) has turned his passion for design and technology into a career. Starting in the early 90s, Thijs started creating ANSI-based user interfaces for dial-up bulletin board systems. With the arrival of the internet, he shifted into frontend design and development. In 2011, he co-founded The Savvy Few, an Amsterdam-based creative digital agency with a strong focus on Drupal. Thijs is an active member of the Drupal community who regularly attends Drupal events across Europe. He divides his time between The Netherlands and Malaysia, where he regularly helps organize local meetups and contribution events for the local Drupal community.
 

drupal
theming
development
planet drupal