Add current page path as a class to body tag (code included)

Created on 23 August 2022, over 2 years ago
Updated 16 August 2024, 3 months ago

I'm using an old version of this theme so you may have fixed this already but I was noticing the body tag does not have the current url of the page which makes customizing the theming a little harder. I noticed you can fix this by adding this to the .theme file:

Under this line...
function openy_carnation_preprocess_html(array &$variables) {

Add

  // Get the current path
  $current_path = \Drupal::service('path.current')->getPath();
  $internal_path = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);

  // Assign it to body class 
  $variables['attributes']['class'][] = str_replace("/", "", $internal_path);

Apologies if you've already fixed this or if this isn't the best way to do this, it worked great for me. Thanks for your hard work!

Feature request
Status

Fixed

Version

2.0

Component

Code

Created by

🇺🇸United States plato1123

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇮🇩Indonesia drupalnesia

    Alternate module: https://www.drupal.org/project/path_alias_class

    This module add classes automatically from website Path and Path Alias. Also you can add Custom CSS.
    For example, if you have a node with title "Training" and NID is 77 then this module will automatically add these classes: training node-77.

    This additional classes will help you easier to modify site appearance using CSS. Now you can styling the "training or node-77" page.

Production build 0.71.5 2024