Is it possible in Drupal 8, to add a CSS class to the <body>
tag based on the current path alias?
2 Answers
In your theme, you can add the following code in template_preprocess_html
:
$current_path = \Drupal::service('path.current')->getPath();
$path_alias = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
$path_alias = ltrim($path_alias, '/');
$variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier($path_alias);
I created the module 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.