Responsive Background Image module offers theme code for paragraphs, but I need it in taxonomy. Taxonomy is a little different in that it is an array inside of an array. How do I change this code to work with Taxonomy instead of Paragraphs?
use Drupal\responsive_background_image\ResponsiveBackgroundImage;
/**
* Implements hook_preprocess_TEMPLATE().
*
* Preprocess paragraph.html.twig.
*/
function mytheme_preprocess_paragraph(&$vars) {
$paragraph = $vars['paragraph'];
$paragraph_type = $paragraph->bundle();
// Add a unique class based on entity ID to all Paragraphs.
// Ideally we should have a unique CSS selector with which to generate the media queries.
// Without a unique selector, you will not be able to have more than one instance
// of the Hero Paragraph on the same page with different background images on each.
$paragraph_id = $paragraph->id();
$css_class = 'paragraph--id--' . $paragraph_id;
$vars['attributes']['class'][] = $css_class;
switch ($paragraph_type) {
// Hero Paragraph.
case 'hero':
// Make sure the image field is not empty.
if (!empty($paragraph->get('field_hero_background_image')
->getValue()[0]['target_id'])) {
// Construct a CSS selector string that points to the element on which a background image will be added.
// In this example, it is assumed that within my Paragraph template there is a div with the class 'hero__image'. Note that we do not have to render the background image in the template itself.
$css_selector = '.' . $css_class . ' .hero__image';
// Here we call the method to generate media queries.
// We pass in the CSS selector string as described above.
// We pass in the entity object.
// We pass in the machine name of the image/media image field.
// We pass in the machine name of the Responsive Image Style.
// In this example, I have a Responsive Image Style called 'hero_paragraph'.
$style_tag = ResponsiveBackgroundImage::generateMediaQueries($css_selector, $paragraph, 'field_hero_background_image', 'hero_paragraph');
// We then check if the media queries were properly generated and attach them to the HTML head.
if ($style_tag) {
$vars['#attached']['html_head'][] = $style_tag;
}
}
break;
}
}