eternalistic
10/11/2016 - 6:59 PM

Add custom class to body based on field value.

Add custom class to body based on field value.

function THEMENAME_preprocess_html(&$variables) {
  // Get the value of the field and add it as a class on <body>.
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    if ($node->field_layout) {
      $layout_style = $node->field_layout->value;
      $vars['attributes']['class'][] = 'layout-' . str_replace('_', '-', $layout_style);
    } else {
      $variables['attributes']['class'][] = 'layout-CUSTOM-CLASS';
    }
  }
}