From af780143bdd93ef84dfc98a20119884be3ccaa28 Mon Sep 17 00:00:00 2001 From: Oskari Kulmala Date: Mon, 31 Aug 2015 15:59:23 +0300 Subject: [PATCH] Get real file uri --- core/lib/Drupal/Core/Template/TwigExtension.php | 56 +++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/core/lib/Drupal/Core/Template/TwigExtension.php b/core/lib/Drupal/Core/Template/TwigExtension.php index 443cf73..f76579d 100644 --- a/core/lib/Drupal/Core/Template/TwigExtension.php +++ b/core/lib/Drupal/Core/Template/TwigExtension.php @@ -12,9 +12,11 @@ namespace Drupal\Core\Template; +use Drupal\image\Entity\ImageStyle; use Drupal\Component\Utility\Html; use Drupal\Component\Utility\SafeMarkup; use Drupal\Component\Utility\SafeStringInterface; +use Drupal\Core\Render\Element; use Drupal\Core\Render\RendererInterface; use Drupal\Core\Routing\UrlGeneratorInterface; use Drupal\Core\Theme\ThemeManagerInterface; @@ -152,6 +154,8 @@ public function getFilters() { new \Twig_SimpleFilter('clean_id', '\Drupal\Component\Utility\Html::getId'), // This filter will render a renderable array to use the string results. new \Twig_SimpleFilter('render', array($this, 'renderVar')), + new \Twig_SimpleFilter('style', array($this, 'getImageStyleUrl')), + new \Twig_SimpleFilter('size', array($this, 'getImageFieldWithStyle')), ); } @@ -514,4 +518,56 @@ public function renderVar($arg) { return $this->renderer->render($arg); } + /** + * 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); + + $query = \Drupal::entityQuery('file') + ->condition('filename', basename($uri), '=') + ->range(0,1); + + $fids = $query->execute(); + + foreach($fids as $fid) { + return $style->buildUrl(\Drupal\file\Entity\File::load($fid)->getFileUri()); + } + } + + /** + * 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; + } } -- 2.3.2 (Apple Git-55)