Forked from jerbob92/ImageRenderExampleBlockByURI.php
Created
February 22, 2017 10:01
-
-
Save slivorezka/33f30498531d60014866f4331cebda53 to your computer and use it in GitHub Desktop.
Render image into a block Drupal 8 Example by URI
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 | |
/** | |
* @file | |
* Contains Drupal\mymodule\Plugin\Block\ImageRenderExampleBlockByURI. | |
*/ | |
namespace Drupal\mymodule\Plugin\Block; | |
use Drupal\Core\Block\BlockBase; | |
use Drupal\file\Entity\File; | |
/** | |
* Provides a 'ImageRenderExampleBlockByURI' block. | |
* | |
* @Block( | |
* id = "mymodule_imagerenderexampleblockbyuri", | |
* admin_label = @Translation("MyModule Image Render Example By URI"), | |
* ) | |
*/ | |
class ImageRenderExampleBlockByURI extends BlockBase { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function build() { | |
$entity_manager = \Drupal::entityManager()->getStorage('file'); | |
$query = $entity_manager->getQuery(); | |
$query->condition('uri', 'public://my-image.jpg'); | |
$fids = $query->execute(); | |
if (count($fids) && $file = File::load(reset($fids))) { | |
$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_build = [ | |
'#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_build, $file); | |
// Return the render array as block content. | |
return [ | |
'logo' => $logo_build, | |
]; | |
} else { | |
// Image not found, return empty block. | |
return []; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment