Problem/Motivation
The theme currently does not generate enough body classes (via html.html.twig) to easily target specific pages or content types for styling. For example, currently, the <body> tag does not include classes indicating whether the page is the frontpage (path-frontpage / path-not-frontpage), the ID of the node being viewed (page-node-[nid]), or the node bundle type (node--type-[bundle]).
Adding these standard Drupal body classes would improve developer experience when styling specific sections or pages of a site.
Steps to reproduce
Proposed resolution
Implement additional preprocessing in hook_preprocess_html() (and expose corresponding helper variables in hook_preprocess_page()) to automatically generate these body classes and template variables.
Here is the implementation code that can be added to the theme:
Preprocess HTML Hook (artisan.theme or includes/html.inc)
use Drupal\Core\Template\Attribute;
use Drupal\node\NodeInterface;
/**
* Implements hook_preprocess_html().
*/
function artisan_preprocess_html(&$variables) {
// Add frontpage body class.
try {
$is_front = \Drupal::service('path.matcher')->isFrontPage();
$front_class = $is_front ? 'path-frontpage' : 'path-not-frontpage';
if ($variables['attributes'] instanceof Attribute) {
$variables['attributes']->addClass($front_class);
}
else {
$variables['attributes']['class'][] = $front_class;
}
}
catch (\Exception $e) {
// Fail-safe if path matcher is not available.
}
// Add node ID and node type body classes.
$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
if (is_numeric($node)) {
$node = \Drupal\node\Entity\Node::load($node);
}
if ($node instanceof NodeInterface) {
$nid_class = 'page-node-' . $node->id();
$type_class = 'node--type-' . $node->bundle();
if ($variables['attributes'] instanceof Attribute) {
$variables['attributes']->addClass($nid_class);
$variables['attributes']->addClass($type_class);
}
else {
$variables['attributes']['class'][] = $nid_class;
$variables['attributes']['class'][] = $type_class;
}
}
}
}
Preprocess Page Hook (artisan.theme or includes/page.inc)
use Drupal\node\NodeInterface;
/**
* Implements hook_preprocess_page().
*/
function artisan_preprocess_page(&$variables) {
if (!empty($variables['node']) && $variables['node'] instanceof NodeInterface) {
$variables['node_id'] = $variables['node']->id();
$variables['node_type'] = $variables['node']->bundle();
}
}
Issue fork artisan-3600848
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #3
alejandro cabarcos commentedComment #6
chikeThanks.
You can add for the user template also cos that has been handy in some projects that have public user profiles.
Comment #8
alejandro cabarcos commentedThanks chike for your suggestions.
Adapted also for the user.
Comment #9
alejandro cabarcos commented