Thursday, November 23, 2017

Drupal 8: Add custom classes to pages using a field value

I have many projects where one special page needs a totally different design than the other pages. So in the css you need a different setup, for instance no right bar with a menu.
I always write the pathname and the node-id to the body classes, but oftentimes you need to change the path of the pages, or you want to add other similarily designed pages to the set and then you need to add those path-classes to the css also, and this all apart from the fact that paths and node ids sometimes diverge in the development environment and the production environment.

The class is strong with this one
So I made a very simple theme preprocess function which simply writes the field value of a custom
field to the bodyclass. This way you can add pages to this special design by simply writing the same class value in that field.
I added a text field 'field_bodyclass' tot the contentypes, and hidden it in the visibility settings for these contentypes. And using this preproces fs function:

function MyModuleOrMyTheme_preprocess_html(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if($node) {
     $variables['attributes']['class'][] = $node->field_bodyclass->value;
 .... other code.....