-
-
Save fazni/cd413504995f74fbc3aad9ce74126383 to your computer and use it in GitHub Desktop.
Drupal 7 and 8 theme image
This file contains hidden or 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 | |
/** | |
* Drupal 7 | |
*/ | |
$fid = 1; | |
$uri = file_load($fid)->uri; // or fetched via the uri property of a field | |
$image_url = image_style_url('thumbnail', $uri); | |
$image = theme_image(array( | |
'path' => $image_url, | |
'alt' => 'my alt', | |
'title' => 'my title', | |
'attributes' => array( | |
'class' => 'my-image', | |
)) | |
); | |
/** | |
* Drupal 8 | |
* @see http://www.vdmi.nl/blog/drupal-8-rendering-image-programmatically | |
*/ | |
$file = File::load(1); | |
$variables = array( | |
'style_name' => 'thumbnail', | |
'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_render_array = [ | |
'#theme' => 'image_style', | |
'#width' => $variables['width'], | |
'#height' => $variables['height'], | |
'#style_name' => $variables['style_name'], | |
'#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_render_array, $file); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment