diff --git a/core/lib/Drupal/Core/Template/TwigExtension.php b/core/lib/Drupal/Core/Template/TwigExtension.php index 520a8be..70c0d54 100644 --- a/core/lib/Drupal/Core/Template/TwigExtension.php +++ b/core/lib/Drupal/Core/Template/TwigExtension.php @@ -6,6 +6,7 @@ use Drupal\Component\Render\MarkupInterface; use Drupal\Core\Cache\CacheableDependencyInterface; use Drupal\Core\Datetime\DateFormatterInterface; +use Drupal\Core\Render\Element; use Drupal\Core\Render\AttachmentsInterface; use Drupal\Core\Render\BubbleableMetadata; use Drupal\Core\Render\Markup; @@ -185,6 +186,9 @@ public function getFilters() { // This filter will render a renderable array to use the string results. new \Twig_SimpleFilter('render', [$this, 'renderVar']), new \Twig_SimpleFilter('format_date', [$this->dateFormatter, 'format']), + + new \Twig_SimpleFilter('style', array($this, 'getImageStyleUrl')), + new \Twig_SimpleFilter('size', array($this, 'getImageFieldWithStyle')), ]; } @@ -630,4 +634,47 @@ public function createAttribute(array $attributes = []) { return new Attribute($attributes); } + /** + * Wrapper around \Drupal\image\ImageStyleInterface::buildUrl(). + * + * @param string $style + * The image style. + * @param string $uri + * Url to image. + * + * @return mixed + * Image url with an image style applied to it. + */ + public function getImageStyleUrl($uri, $style) { + $style = entity_load('image_style', $style); + return $style->buildUrl($uri); + } + + /** + * Function that returns a renderable array of an image field with a given + * image style. + * + * @param $field + * Renderable array of a field. + * @param $style + * an image style. + * + * @return mixed + * a renderable array or NULL if there is no valid input. + */ + public function getImageFieldWithStyle($field, $style) { + if(!isset($field['#field_type']) || $field['#field_type'] !== 'image') { + return NULL; + } + + $element_children = Element::children($field, TRUE); + + if(!empty($element_children)) { + foreach ($element_children as $delta => $key) { + $field[$key]['#image_style'] = $style; + } + } + + return $field; + } }