Skip to content

Instantly share code, notes, and snippets.

@szeidler
Created March 15, 2016 08:42
Show Gist options
  • Save szeidler/3526f21a89f93a318e5d to your computer and use it in GitHub Desktop.
Save szeidler/3526f21a89f93a318e5d to your computer and use it in GitHub Desktop.
Load and render responsive image from field in Drupal 8
<?php
function _load_header_image($variables) {
if ($node = $variables['node']) {
// Load main_image
$file = $node->field_main_image->entity;
if ($file) {
$variables = array(
'responsive_image_style_id' => 'header_image',
'uri' => $file->getFileUri(),
);
// The image.factory service will check if our image is valid.
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
$variables['width'] = $image->getWidth();
$variables['height'] = $image->getHeight();
}
else {
$variables['width'] = $variables['height'] = NULL;
}
$logo_build = [
'#theme' => 'responsive_image',
'#width' => $variables['width'],
'#height' => $variables['height'],
'#responsive_image_style_id' => $variables['responsive_image_style_id'],
'#uri' => $variables['uri'],
];
// Add the file entity to the cache dependencies.
// This will clear our cache when this entity updates.
$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($logo_build, $file);
// Return the render array as block content.
return $logo_build;
}
}
return NULL;
}
@halkhalil
Copy link

//reference field for a media entity, with multiple values.

function MYTHEME_preprocess_node__CONTENT_TYPE(&$variables) {
  $display_options = [
    'label'    => 'hidden',
    'type'     => 'responsive_image',
    'settings' => [
      'responsive_image_style' => 'property_hero',
    ],
  ];
  foreach ($variables['node']->get('field_hero_images')->getValue() as $key => $value) {
    $media = Media::load($value['target_id']);
    $responsive_image = $media->field_media_image->view($display_options);
    $variables['hero_images'][] = [
      'hero_image' => $responsive_image
    ];
  }
}

@vistree
Copy link

vistree commented Mar 9, 2022

Hi, I like the approach from @leymannx
Any chance to add a class to the responsive image?
In twig you can add a class to responsive image style using:
{% set responsiveImage = {
'#theme': 'responsive_image',
'#responsive_image_style_id': 'display_image_gallery',
'#uri': imagePath,
'#alt': altText,
'#attributes': { class: 'img-responsive' },
} %}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment