You are here

public static function Blazy::preprocessResponsiveImage in Blazy 8

Same name and namespace in other branches
  1. 8.2 src/Blazy.php \Drupal\blazy\Blazy::preprocessResponsiveImage()

Overrides variables for responsive-image.html.twig templates.

2 calls to Blazy::preprocessResponsiveImage()
BlazyManagerTest::testPreprocessResponsiveImage in tests/src/Kernel/BlazyManagerTest.php
Tests responsive image integration.
blazy_preprocess_responsive_image in ./blazy.module
Overrides variables for responsive-image.html.twig templates.

File

src/Blazy.php, line 405

Class

Blazy
Implements BlazyInterface.

Namespace

Drupal\blazy

Code

public static function preprocessResponsiveImage(&$variables) {
  $image =& $variables['img_element'];
  $attributes =& $variables['attributes'];

  // Prepare all <picture> [data-srcset] attributes on <source> elements.
  if (!$variables['output_image_tag']) {

    /** @var \Drupal\Core\Template\Attribute $source */
    if (isset($variables['sources']) && is_array($variables['sources'])) {
      foreach ($variables['sources'] as &$source) {
        $source
          ->setAttribute('data-srcset', $source['srcset']
          ->value());
        $source
          ->removeAttribute('srcset');
      }
    }

    // Fetches the picture element fallback URI, and empty it later.
    // These address both 8.x-2 and 8.x-3 compatibility.
    $fallback_uri = isset($image['#srcset'], $image['#srcset'][0]['uri']) ? $image['#srcset'][0]['uri'] : $image['#uri'];

    // Prevents invalid IMG tag when one pixel placeholder is disabled.
    $image['#uri'] = static::PLACEHOLDER;
    $image['#srcset'] = '';

    // Cleans up the no-longer relevant attributes for controlling element.
    unset($attributes['data-srcset'], $image['#attributes']['data-srcset']);
  }
  else {
    $fallback_uri = $image['#uri'];
    $attributes['data-srcset'] = $attributes['srcset']
      ->value();
    $image['#attributes']['data-srcset'] = $attributes['srcset']
      ->value();
    $image['#attributes']['srcset'] = '';
  }

  // Blazy needs controlling element to have fallback [data-src], else error.
  $image['#attributes']['data-src'] = $fallback_uri;
  $image['#attributes']['class'][] = 'b-lazy b-responsive';

  // Only replace fallback image URI with 1px placeholder, if so configured.
  // This prevents double-downloading the fallback image.
  if (!empty($attributes['data-b-lazy'])) {
    $image['#uri'] = static::PLACEHOLDER;
  }
  unset($attributes['data-b-lazy'], $image['#attributes']['data-b-lazy']);
}