Forked from szeidler/d8-responsive-image-programmatically.php
Last active
July 16, 2021 17:35
-
-
Save megclaypool/ecd71dd2759b8efd95ff279966470baf to your computer and use it in GitHub Desktop.
[How to render Drupal image field items(as responsive image!) programmatically -- PHP ] Load and render responsive image from field in Drupal 8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm just forking this to preserve it in case the original gets deleted. This code saved my bacon today!