Comments

wilei’s picture

+1 for this one.

I can come up with some cases when this feature is needed. At least when working with custom entities when views and/or fields may not be available, this feature would be very nice.

Cottser’s picture

It's going to be a bit more complicated than some of the other Twig extensions we have but shouldn't be too bad, I think you'd end up with something like this in a Twig extension (rough pseudo code):

$style = entity_load('image_style', $style);
return $style->buildUrl($uri);

This should also be doable in preprocess, so I'm not sure about this: "the task can only be accomplished through the use of contrib modules in conjunction with views."

dmdewey’s picture

Issue summary: View changes

removed "and the task can only be accomplished through the use of contrib modules in conjunction with views"

Cottser’s picture

Title: Twig image style filter » Twig image style filter/function
Parent issue: » #2168231: Twig Functions needed in templates
dawehner’s picture

Its not really clear for me why we don't just expose image_style_url, as it is. It would be great to document that in the issue summary.

Cottser’s picture

Because the function doesn't exist in D8.

image_style_url()

dawehner’s picture

Ups :) Well, maybe its also enough to wrap


$style = entity_load('image_style', $style);
return $style->buildUrl($uri);

in some nice little helper function?

dawehner’s picture

This issue as marked as feature request, but at the same time it blocks #2168231: Twig Functions needed in templates.
Does this mean this issue is also a bug?

mortendk’s picture

Issue tags: +image

any progress on this or did i miss something ?
it would be pretty amazing if we could do something like this inside of a template

<a href="#">{{ content.image|image-size('small')}}</a>
<div class="secret-hidden-will-be-shown-later-with-css-cause-we-want-a-imagegallery">
  {{ content.image|image-size('large')}}
</div>
JeroenT’s picture

Assigned: Unassigned » JeroenT

Will work on this tomorrow. If anyone beats me to it, feel free to unassign me.

harshil.maradiya’s picture

I would like to work on this but before this i want to discus my approach

Please correct me if i am wrong

  • Introduce filters in twigextenstion.php
  • And declare method in twigextenstion.php

Regards
Harshil Maradiya

JeroenT’s picture

Assigned: JeroenT » Unassigned
Status: Active » Needs review
FileSize
1.11 KB
PASSED: [[SimpleTest]]: [PHP 5.5 MySQL] 101,464 pass(es). View

First attempt on creating the twig filter.

Patch attached.

mortendk’s picture

Status: Needs review » Needs work
Issue tags: +needs manua

created a image.html.twig template

<img{{ attributes|without('src')}} src="{{ attributes.src|style('medium') }}" />

unfortunately it dosnt render the image

<img property="schema:image" width="480" height="320" alt="coffee" typeof="foaf:Image" src="http://styles/medium/http/drupal8.dev/sites/default/files/styles/large/public/field/image/coffee.jpg?itok=nJshh3GG&amp;itok=03bZfNJF">

cause this is the return path to the image
http://styles/medium/http/drupal8.dev/sites/default/files/styles/large/public/field/image/coffee.jpg?itok=nJshh3GG&itok=03bZfNJF

guess something needs to get done to that path (styles/medium/http/)?

JeroenT’s picture

Status: Needs work » Needs review
FileSize
2.17 KB
PASSED: [[SimpleTest]]: [PHP 5.5 MySQL] 102,542 pass(es). View
1.54 KB

Created a new patch that a size filter like this:

<a href="#">{{ content.image|image-size('small')}}</a>
<div class="secret-hidden-will-be-shown-later-with-css-cause-we-want-a-imagegallery">
  {{ content.image|image-size('large')}}
</div>

I haven't addressed the bug in #13.

The following code passes an absolute url in the twig filter but \Drupal\image\Entity\ImageStyle::buildUrl() expects an uri. Not sure how to solve this.

<img{{ attributes|without('src')}} src="{{ attributes.src|style('medium') }}" />
JeroenT’s picture

Issue tags: -needs manua +Needs manual testing
mortendk’s picture

Issue summary: View changes
Status: Needs review » Needs work
FileSize
269.36 KB

@JeroenT i tested it out lemme know if i do something stupid ;)

use the image.html.twig template wonder if im doing something wrong ?

andriyun’s picture

Issue tags: -Needs manual testing

Manual testing done. So I remove proper tag

oakulm’s picture

Issue summary: View changes

Ok some thoughts after DC Baltics sprint about this issue. My idea is that to use these filters you should send original image to template and in the template decide what preset to use (instead of in the field setting). Am I correct?

The main issue is (I think) the fact that attributes.src returns absolute path to file. What I set out to do and failed was to find a method that finds file object from filename or absolute url (or what ever is the method in D8) and parses file path to schema:// format. Does anyone know does this exist? If it does than I think this problem is trivial to fix.

oakulm’s picture

+++ b/core/lib/Drupal/Core/Template/TwigExtension.php
@@ -513,4 +516,47 @@ public function renderVar($arg) {
+   * @param string $style
...
+   * @param string $uri

These parameters are not strings at the moment if used with {{ attributes.src|style('example') }}

oakulm’s picture

FileSize
2.84 KB
FAILED: [[SimpleTest]]: [PHP 5.5 MySQL] Unable to apply patch twig_image_style-2361299-20.patch. Unable to apply patch. See the log in the details link for more information. View

Ok this patch works with:

{{ attributes.src|style('large')}}
<img{{ attributes|without('src', 'height', 'width')}} src="{{ attributes.src|style('large') }}" />

Don't really know if this is the right direction to take?

oakulm’s picture

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 20: twig_image_style-2361299-20.patch, failed testing.

pjonckiere’s picture

I think the mechanic of fetching the file based on the filename is flawed. What would happen when two images have the same name, but are different?

  1. +++ b/core/lib/Drupal/Core/Template/TwigExtension.php
    @@ -514,4 +518,56 @@ public function renderVar($arg) {
    +   * Wrapper around \Drupal\image\ImageStyleInterface::buildUrl().
    

    This comment is no longer relevant?

  2. +++ b/core/lib/Drupal/Core/Template/TwigExtension.php
    @@ -514,4 +518,56 @@ public function renderVar($arg) {
    +   * @param string $style
    +   *   The image style.
    

    This is not a string, but a Drupal\image\Entity\ImageStyle object.

  3. +++ b/core/lib/Drupal/Core/Template/TwigExtension.php
    @@ -514,4 +518,56 @@ public function renderVar($arg) {
    +   * @param string $uri
    +   *   Url to image.
    

    This is not a string but a \Drupal\Core\Template\AttributeString object.

  4. +++ b/core/lib/Drupal/Core/Template/TwigExtension.php
    @@ -514,4 +518,56 @@ public function renderVar($arg) {
    +   * @return mixed
    

    This would be a string or nothing at all.

  5. +++ b/core/lib/Drupal/Core/Template/TwigExtension.php
    @@ -514,4 +518,56 @@ public function renderVar($arg) {
    +      ->condition('filename', basename($uri), '=')
    

    The basename() function could return myfile.png?foo=bar, which would make that query fail?

  6. +++ b/core/lib/Drupal/Core/Template/TwigExtension.php
    @@ -514,4 +518,56 @@ public function renderVar($arg) {
    +    $query = \Drupal::entityQuery('file')
    ...
    +      ->range(0,1);
    

    Actually, what happens when you have to different images with the same filename? I don't think this would work as expected?

tuutti’s picture

FileSize
4.51 KB
FAILED: [[SimpleTest]]: [PHP 5.5 MySQL] 113,531 pass(es), 5 fail(s), and 8 exception(s). View

I spoke with @lauriii little bit about this and one possible way to implement this would be by adding 'original_uri' (or something similar) render array item and populate it with file uri.

lauriii’s picture

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 24: 2361299-24.patch, failed testing.

The last submitted patch, 24: 2361299-24.patch, failed testing.

pwolanin’s picture

Version: 8.0.x-dev » 8.1.x-dev
Issue tags: +Needs issue summary update

features need to go to 8.1 now

Version: 8.1.x-dev » 8.2.x-dev

Drupal 8.1.0-beta1 was released on March 2, 2016, which means new developments and disruptive changes should now be targeted against the 8.2.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Virang’s picture

Can we override this TwigExtension.php with custom module? as above mentioned path for patch is core/lib/Drupal/Core/Template/TwigExtension.php.

Please suggest me I just started learning Drupal 8.

morbidick’s picture

FileSize
2.24 KB

I just tried patch #14 and modified it for the current version 8.1.2. For now I only could test the size filter which works fine.
A custom module or to get the filter in to core would be awesome.

morbidick’s picture

Version: 8.2.x-dev » 8.3.x-dev

Drupal 8.2.0-beta1 was released on August 3, 2016, which means new developments and disruptive changes should now be targeted against the 8.3.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

pounard’s picture

I have no particular opinion about this patch except the fact that entity_load() procedural call is done inside a service, you should probably add the entity.manager service injection instead.

kamalMaroc’s picture

To get image by style, first you need to create an extension of twig, that can load image by your parameters (large, thumbnail ...etc) :

1- In your custom module create file "Image.php" in "/modules/custom/your_module/src/TwigExtension

<?php
namespace Drupal\your_module\TwigExtension;

use Drupal\node\Entity\Node;
use Drupal\Core\Link;
use Drupal\Core\Url;

use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;

class Images extends \Twig_Extension {
  /**
   * Generates a list of all Twig functions that this extension defines.
   */
  public function getFunctions(){
    return array(
      new \Twig_SimpleFunction('image_style', array($this, 'imageStyle'), array('is_safe' => array('html'))),
    );
  }

  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName() {
    return 'your_module.twig.images';
  }


  /**
   * Generate images styles for given image
   */
  public static function imageStyle($file_id, $styles) {
    $file = File::load($file_id);
    $transform = array();
    if (isset($file->uri->value)) {
      $transform['source'] = $file->url();
      foreach ($styles as $style) {
        $transform[$style] = ImageStyle::load($style)->buildUrl($file->uri->value);
      }
    }
    return $transform;
  }
}

2- In root folder create file service "/modules/custom/your_module/your_module.services.yml

services:
  your_module.twig.images:
    #arguments: ['@renderer']
    class: Drupal\your_module\TwigExtension\Images
    tags:
      - { name: twig.extension }

3- Delete a cache

4- Finally you can use extension in twig file like this :

{% set image = image_style(node.field_image.entity.fid.value, ['large']) %}
<img src="{{ image.large }}" >

Good Luck.

ichionid’s picture

"/modules/custom/your_module/your_module.services.yml.php" @kamalMaroc this should not have a php ending. Pretty nice and detailed guide :-)

harry_nc’s picture

1- In your custom module create file "Image.php" in "/modules/custom/your_module/src/TwigExtension

- Images.php**

With that and #36, works a treat thanks man!

featherbelly’s picture

@kamalMaroc This works great!

#35 + #36 + #37

Rene Bakx’s picture

If you want a installable solution, I am willing to add the code of Kamel or improved version to the Themers Little Helper project.
There is a similar twig function in TFD7, and I do think having a plain file to image style mapper can come in handy sometimes.

The only thing I would probably change is signature of the method, instead of relying on the fid.value, I would prefer to just pass the entire field to twig function and let the function figure out if it got a FID, File entity or renderable array)

<img src="{{ image_style(content.field_image,'large') }}">

Version: 8.3.x-dev » 8.4.x-dev

Drupal 8.3.0-alpha1 will be released the week of January 30, 2017, which means new developments and disruptive changes should now be targeted against the 8.4.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

basvanderheijden’s picture

FileSize
2.22 KB

I've re-created the patch for 8.3.5

gaurav.kapoor’s picture

Status: Needs work » Needs review