You are here

public static function Blazy::buildImage in Blazy 8

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

Modifies variables for regular image.

1 call to Blazy::buildImage()
Blazy::buildAttributes in src/Blazy.php
Prepares variables for blazy.html.twig templates.

File

src/Blazy.php, line 96

Class

Blazy
Implements BlazyInterface.

Namespace

Drupal\blazy

Code

public static function buildImage(array &$variables) {
  $image =& $variables['image'];
  $settings =& $variables['settings'];
  $attributes =& $variables['attributes'];
  $image_attributes =& $variables['item_attributes'];

  // Supports non-lazyloaded image.
  $image['#theme'] = 'image';

  // Supports either lazy loaded image, or not, which is overriden later.
  // This allows Blazy to be used for RSS by disabling $settings['lazy']
  // and $settings['view_mode'] = 'rss' via hook_blazy_settings_alter()
  // since image_url is not transformed relative.
  $image['#uri'] = empty($settings['image_url']) ? $settings['uri'] : $settings['image_url'];

  // Aspect ratio to fix layout reflow with lazyloaded images responsively.
  // This is outside 'lazy' to allow non-lazyloaded iframes use this too.
  if (!empty($settings['width'])) {
    if (!empty($settings['ratio']) && in_array($settings['ratio'], [
      'enforced',
      'fluid',
    ])) {
      $padding_bottom = empty($settings['padding_bottom']) ? round($settings['height'] / $settings['width'] * 100, 2) : $settings['padding_bottom'];
      $attributes['style'] = 'padding-bottom: ' . $padding_bottom . '%';
      $settings['_breakpoint_ratio'] = $settings['ratio'];
    }
  }

  // Supports lazyloaded image.
  if (!empty($settings['lazy'])) {
    $image['#uri'] = static::PLACEHOLDER;

    // Attach data attributes to either IMG tag, or DIV container.
    if (empty($settings['background']) || empty($settings['blazy'])) {
      self::buildBreakpointAttributes($image_attributes, $settings);
    }

    // Supports both Slick and Blazy CSS background lazyloading.
    if (!empty($settings['background'])) {
      self::buildBreakpointAttributes($attributes, $settings);
      $attributes['class'][] = 'media--background';

      // Blazy doesn't need IMG to lazyload CSS background. Slick does.
      if (!empty($settings['blazy'])) {
        $image = [];
      }
    }

    // Multi-breakpoint aspect ratio only applies if lazyloaded.
    if (!empty($settings['blazy_data']['dimensions'])) {
      $attributes['data-dimensions'] = Json::encode($settings['blazy_data']['dimensions']);
    }
  }
}