Failing to implement this on a node

Created on 30 March 2020, over 4 years ago
Updated 24 June 2024, 10 days ago

Thanks for this module. It seems to be the only one actively maintained and offering Core Media Field support. :)

I have tried to implement this using the example provided in the documentation.. but failed miserably. I am not using Paragraphs so I would like to implement this on a node.

Steps taken:

Installed and enabled 1.x-dev
Created .theme file with preprocess function as follows:

<?php

/**
 * @file
 * Functions to support theming in the MyTheme theme.
 */

use Drupal\responsive_background_image\ResponsiveBackgroundImage;

/**
 * Implements hook_preprocess_TEMPLATE().
 *
 * Preprocess node.html.twig.
 */
function MyTheme_preprocess_node(&$vars) {
  $node = $vars['node'];
  $node_type = $node->getType();

  // Add a unique class based on entity ID to all nodes.
  // 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 node on the same page with different background images on each.
  $node_id = $node->id();
  $css_class = 'node--id--' . $node_id;
  $vars['attributes']['class'][] = $css_class;

  switch ($node_type) {

    // Diary node.
    case 'diary':
      // Make sure the image field is not empty.
      if (!empty($node->get('field_cover_media')
        ->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 node 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 . ' .block-page-title-block';

        // 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_node'.
        $style_tag = ResponsiveBackgroundImage::generateMediaQueries($css_selector, $node, 'field_cover_media', 'hero_image');

        // 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;
   }

Where:

diary = Content Type machine name.
field_cover_media = Machine name of Entity Reference field on content type diary. This field references an Image Media Type
.block-page-title-block = Class of a standard, existing div for troubleshooting purposes
hero_image = Responsive Image Style created for this purpose

Result: No background shown. <html> and code> tags do not show to be expected code (as shown in documentation).

Where did I go wrong?

πŸ’¬ Support request
Status

Closed: outdated

Version

1.0

Component

Miscellaneous

Created by

πŸ‡¦πŸ‡ΊAustralia RedTop

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡¨πŸ‡¦Canada plousia

    I had to do this and thought I'd write it up for those who may be looking for the same thing. Note that this setup is assuming a single-value image or image media entity reference field on a node, so you don't need to add unique IDs or anything like that as you do with Paragraphs where you may have more than one on the same page.

    /**
    * Implements template_preprocess_node().
    */
    
    function MYTHEME_preprocess_node(&$vars) {
      $node = $vars['node'];
      $type = $node->bundle();
    
      switch ($type) {
        // here you will need to replace 'landing_page' with the machine name of your content type
        case 'landing_page':
          // Make sure the image field is not empty.
         // Replace 'field_hero_image' with your content type's image field machine name
          if (!empty($node->get('field_hero_image')->getValue()[0]['target_id'])) {
         // in your node or page template, you will need to add a div with the class "page-hero". Change this class name if needed to whatever you want to use
            $css_selector = ' .page-hero';
    
            // 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 'fullscreen_hero'.
           // Replace the field machine name and the responsive image style machine name to whatever you are using.
            $style_tag = ResponsiveBackgroundImage::generateMediaQueries($css_selector, $node, 'field_hero_image', 'fullscreen_hero');
    
            // 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;
       }
    }
    

    You can also do this in a page preprocess function if you want, although if you use node preprocess and just put a div with the correct CSS class in your page template, it will still work. Here's the page preprocess function, you just need to check if it's a node page:

    /**
    * Implements template_preprocess_page().
    */
    function MYTHEME_preprocess_page(&$vars) {
      $node = $vars['node'];
    
      if($node) {
        $type = $node->bundle();
    
        switch ($type) {
        case 'landing_page':
          // Make sure the image field is not empty.
          if (!empty($node->get('field_hero_image')->getValue()[0]['target_id'])) {
            $css_selector = ' .page-hero';
    
            $style_tag = ResponsiveBackgroundImage::generateMediaQueries($css_selector, $node, 'field_hero_image', 'fullscreen_hero');
    
            if ($style_tag) {
              $vars['#attached']['html_head'][] = $style_tag;
            }
          }
    
          break;
        }
      }
    }
    
  • πŸ‡¨πŸ‡¦Canada plousia

    @ maintainer, this might be useful to add to the documentation.

Production build 0.69.0 2024