function template_preprocess_responsive_image_formatter

Same name and namespace in other branches
  1. 9 core/modules/responsive_image/responsive_image.module \template_preprocess_responsive_image_formatter()
  2. 8.9.x core/modules/responsive_image/responsive_image.module \template_preprocess_responsive_image_formatter()
  3. 10 core/modules/responsive_image/responsive_image.module \template_preprocess_responsive_image_formatter()

Prepares variables for responsive image formatter templates.

Default template: responsive-image-formatter.html.twig.

Parameters

array $variables: An associative array containing:

  • item: An ImageItem object.
  • item_attributes: An optional associative array of HTML attributes to be placed in the img tag.
  • responsive_image_style_id: A responsive image style.
  • url: An optional \Drupal\Core\Url object.

File

core/modules/responsive_image/responsive_image.module, line 90

Code

function template_preprocess_responsive_image_formatter(&$variables) {
    // Provide fallback to standard image if valid responsive image style is not
    // provided in the responsive image formatter.
    $responsive_image_style = ResponsiveImageStyle::load($variables['responsive_image_style_id']);
    if ($responsive_image_style) {
        $variables['responsive_image'] = [
            '#type' => 'responsive_image',
            '#responsive_image_style_id' => $variables['responsive_image_style_id'],
        ];
    }
    else {
        $variables['responsive_image'] = [
            '#theme' => 'image',
        ];
    }
    $item = $variables['item'];
    $attributes = [];
    // Do not output an empty 'title' attribute.
    if (!is_null($item->title) && mb_strlen($item->title) != 0) {
        $attributes['title'] = $item->title;
    }
    $attributes['alt'] = $item->alt;
    // Need to check that item_attributes has a value since it can be NULL.
    if ($variables['item_attributes']) {
        $attributes += $variables['item_attributes'];
    }
    if (($entity = $item->entity) && empty($item->uri)) {
        $variables['responsive_image']['#uri'] = $entity->getFileUri();
    }
    else {
        $variables['responsive_image']['#uri'] = $item->uri;
    }
    foreach ([
        'width',
        'height',
    ] as $key) {
        $variables['responsive_image']["#{$key}"] = $item->{$key};
    }
    $variables['responsive_image']['#attributes'] = $attributes;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.