Drupalwoo ☉

Building a Drupal module for custom body classes

Body classes are small CSS hooks that give a Drupal site stable context without changing its content structure. They support design-system rules, targeted JavaScript, accessibility states, and campaign styling while keeping selectors out of Twig templates. This article follows the practical route for building a Drupal module that adds custom body classes per node type, from module metadata through preprocessing, configuration, and release checks.

Australian editorial teams often have reasons to separate content by meaning, not merely by layout. A Sydney publisher might use news_article, while a Melbourne organisation uses service_page and a Brisbane council uses council_service. The resulting classes can support an Australia Day campaign, an end-of-financial-year feature, or an Australian market page carrying AUD pricing. Naming and spelling remain consistent, while dates can stay in the preferred day-first format without relying on CSS to reformat them.

How body classes reach rendered pages

Drupal’s default html.html.twig template renders attributes on the <body> element. Those attributes may already include classes such as the current path, language, or front-end status. A module can extend that collection during the HTML preprocessing stage rather than replacing the template or duplicating markup in every content type.

This matters because the body class is useful only if the final element contains it. A rule such as body.node-type-landing-page .region-content can change spacing, background treatment, or component styling for one kind of node. Another rule could expose the bundle to JavaScript through document.body.classList, while a third could apply a campaign treatment without affecting administrative pages.

The appropriate Drupal API is hook_preprocess_html(). A module named node_body_classes implements it through the function node_body_classes_preprocess_html(). Adding a value to $variables['attributes']['class'] places it in the body’s class attribute during rendering. This approach avoids a fragile template override and remains compatible with themes that follow Drupal’s standard body-attribute structure.

Creating a small custom module

Start with a directory under the site’s custom module directory, such as web/modules/custom/node_body_classes. The minimal implementation needs an information file, a module file, and an optional configuration file:

node_body_classes/
├── node_body_classes.info.yml
├── node_body_classes.module
└── config/
    └── install/
        └── node_body_classes.settings.yml

The information file identifies the module and its compatible Drupal versions:

name: 'Node body classes'
type: module
description: 'Adds configurable CSS classes for Drupal node bundles.'
package: 'Custom'
core_version_requirement: ^10 || ^11

The module file contains the preprocessing function. It can be enabled through the Drupal administration interface or with drush pm:enable node_body_classes. No service container entry is needed for this small implementation, although a larger module might move the bundle-to-class resolution into a dedicated service with dependency injection.

A complementary Drupalwoo example is its dynamic sitemap walkthrough, which demonstrates how a focused custom module can combine Drupal extension points with practical site output.

Mapping node types to configurable classes

A stable class should be based on the node bundle’s machine name rather than its editable label. Renaming “Landing Page” to “Campaign Page” should not unexpectedly break a stylesheet. Configuration lets editors associate additional design or campaign classes with each bundle while the module supplies a predictable default.

Create config/install/node_body_classes.settings.yml with a mapping like this:

classes:
  article:
    - article
    - content-article
  landing_page:
    - landing-page
  service_page:
    - service-page

The module then reads the active configuration and adds both the configured classes and a generated node-type-* class:

<?php

use Drupal\Core\Entity\NodeInterface;

function node_body_classes_preprocess_html(array &$variables): void {
  $node = \Drupal::routeMatch()->getParameter('node');

  if (!$node instanceof NodeInterface) {
    return;
  }

  $bundle = $node->bundle();
  $map = \Drupal::config('node_body_classes.settings')->get('classes') ?? [];
  $classes = $map[$bundle] ?? [];

  if (!is_array($classes)) {
    $classes = [$classes];
  }

  $classes[] = 'node-type-' . strtolower(str_replace('_', '-', $bundle));

  foreach (array_unique($classes) as $class) {
    if (is_string($class) && preg_match('/^[a-z][a-z0-9_-]*$/', $class)) {
      $variables['attributes']['class'][] = $class;
    }
  }
}

Validation matters because a malformed CSS class can produce broken selectors or unexpected attribute values. The regular expression accepts lowercase letters, numbers, underscores, and hyphens while rejecting spaces and punctuation. Configuration deployment can manage the mapping across environments; an administration form can be added later if non-technical editors need to change it.

Handling routes, caching, and real-world requests

On a normal node route, Drupal’s route match supplies the node parameter as a NodeInterface object. The module can therefore identify the bundle without running a separate database query. Node aliases still use the underlying entity route, so the same class appears at /node/12 and at a friendly path such as /updates/sydney-office.

Listing routes and custom views do not necessarily have one node parameter. In that situation, the module leaves the body unchanged, which prevents a list of mixed bundles from receiving a misleading class. A custom route that exposes only a numeric nid needs a route converter or parameter resolver if the same behaviour is required there. Previews, print views, feeds, and error pages should also be checked because their route context can differ.

Caching requires particular attention. Drupal’s dynamic page cache can store the complete response for anonymous visitors, including its generated body classes. Because the result is bundle-based rather than user-specific, it can be shared safely, but changing the configuration requires relevant cache invalidation. Test anonymous and authenticated views, clear caches after deployment, and confirm that a cached page still contains the expected class.

When JavaScript consumes these hooks, keep DOM assumptions narrow; a separate client-side development reference can help compare runtime approaches, but the server-rendered class should remain the source of truth. Locale and time-zone presentation also belong in Drupal configuration. An Australian site may use en-AU, day-first dates, and AEST or AEDT, while a body class such as locale-en-au can support presentation rules without trying to convert timestamps in CSS.

Comparing patterns and release checks

Keep generated identifiers predictable and use supplementary classes for shared design contexts. A generated bundle class handles specificity, while a section or campaign class can be reused across several content types.

Useful class patterns

Testing should cover the rendered HTML rather than only the CSS editor. Inspect the <body> element directly, because a selector that appears correct in a theme may target a wrapper instead.

Checks before publishing

The practical options differ in where they resolve context and how much work they create for future Drupal upgrades.

Approach Context source Multiple classes Upgrade burden Strongest use
Module preprocess hook Route-matched node object Yes Low Shared bundle behaviour
Theme preprocess hook Theme and route context Yes Medium Theme-specific styling
Core HTML template override Custom Twig template Possible High Exceptional layout requirements
Client-side JavaScript DOM or data attributes Yes Medium Progressive enhancement

For reusable Drupal behaviour, a module preprocess hook with configuration offers the strongest balance: it produces server-rendered classes, avoids core template overrides, and remains straightforward to test and maintain across Australian sites with different content structures.