Sometimes it's handy to have the node id in the <body> tag so you can add some custom styling to a specific page. The result would look like this (if the node id was 123).
<body class="page-node-123">
There will be other theme specific classes so we need to add ours rather than overwriting anything that already exists. This is done using THEME_preprocess_html()
If my theme was myD9theme then this would be in the myD9theme.theme file.
function myD9theme_preprocess_html(&$variables) { if ($node = \Drupal::request()->attributes->get('node')) { $variables['attributes']['class'][] = 'page-node-' . $node->id(); } }
This can be expanded to add the content type too as we already have $node. The extra line is $variables['attributes']['class'][] = $node->bundle(); so the final code would be:
function myD9theme_preprocess_html(&$variables) { if ($node = \Drupal::request()->attributes->get('node')) { $variables['attributes']['class'][] = 'page-node-' . $node->id(); $variables['attributes']['class'][] = $node->bundle(); } }
Note: content types will have an underscore between words if they consist of more than one word, so a content type of 'Video Channel' would become 'video_channel' and the final <body> tag would be:
<body class="page-node-123 video_channel">
Remember to rebuild the cache or your new code won't be read!