Skip to content

Instantly share code, notes, and snippets.

@normanlolx
Created October 17, 2017 13:59
Show Gist options
  • Save normanlolx/3df383b3dc955f0332e53f140512bdaa to your computer and use it in GitHub Desktop.
Save normanlolx/3df383b3dc955f0332e53f140512bdaa to your computer and use it in GitHub Desktop.
Drupal 8 load and render responsive image field inside a block programmatically
<?php
namespace Drupal\abc_header\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a 'ABC Hero Image' Block.
*
* @Block(
* id = "abc_hero_image_block",
* admin_label = @Translation("ABC Hero Image"),
* category = @Translation("ABC"),
* context = {
* "node" = @ContextDefinition(
* "entity:node",
* label = @Translation("Current Node")
* )
* }
* )
*/
class HeroImageBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return ['label_display' => FALSE];
}
/**
* {@inheritdoc}
*/
public function build() {
$node = $this->getContextValue('node');
$display_options = [
'label' => 'hidden',
'type' => 'responsive_image',
'settings' => [
'responsive_image_style' => 'hero_image',
],
];
$hero_image = $node->get('field_hero_image')->view($display_options);
return [
'#type' => 'markup',
'#markup' => render($hero_image),
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment