Drupal: add current_path & path_alias to body tag of page HTML

web/themes/custom/mycustomtheme/mycustomtheme.theme:

function MYCUSTOMTHEME_preprocess_html(&$variables) {
    $current_path = \Drupal::service('path.current')->getPath();
    $path_alias = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
    
    $current_path_ascii = preg_replace("#[^a-z0-9]#simU","", $current_path);
    
    $variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier($current_path_ascii ); 
    
    $variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier( ltrim($path_alias, '/') );
   
}

Output:

<body class="node123 my/custom/path/for/node/123 user-logged-in path-node page-node-type-article">

Neuen Kommentar schreiben

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

Suche

Neueste Kommentare