3

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.

4

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.

  • Thanks it works on normal fields. I just alter the solution. I uploaded mine just in case. – Mudassar Ali Aug 25 '16 at 6:28
2

In case if you don't want to touch you template file. /** * * Implementation of theme_preprocess_html(). */ function school_preprocess_html(&$variables) { if ($variables['node_type'] === 'article') { $node = \Drupal::routeMatch()->getParameter('node'); if ($node->media_image->getValue()) { $variables['attributes']['class'][] = 'collection-has-image'; } } } 1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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