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.
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.
$node->field_image->entity
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';
}
}
}