4

I need to add class in body when content type article and have image on it. How do I achieve this?

I checked in theme_preprocess_html only found content_type as string. Don't know how to check image on it.

2 Answers 2

5

You will need to do a little work in the html preprocess:

/**
 * Implements template_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {
  $variables['has_image'] = FALSE;
  if ($variables['node_type'] == 'article' && ($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
    $variables['has_image'] = empty($node->field_image->value) ? FALSE : TRUE;
  }
}

and the html template:

{#
/**
 * @file html.html.twig
 */
#}
<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
...
  </head>
  <body{{ attributes.addClass(has_image ? ['has-image']) }}>

This will add the class has-image to the body tag of every Article type content node.

2
  • Thanks it works on normal fields. I just alter the solution. I uploaded mine just in case. Commented Aug 25, 2016 at 6:28
  • 1
    Little addition: for media files use: $node->field_image->entity
    – Lance
    Commented Dec 3, 2021 at 10:58
3

In case you don't want to touch your template file.

/**
 * Implements hook_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {
  if ($variables['node_type'] === 'article') {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node->field_image->getValue()) {
      $variables['attributes']['class'][] = 'has-image';
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.