Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Hi - I am wondering whether it is possible to add a filter for using a responsive image set in a similar way to how this great module currently works for an image style?
Eg:
<dt>Responsive image style:</dt>
<dd>{{ 'public://images/ocean.jpg' | responsive_image_style('narrow') }}</dd>
I have tried to come up with something but so far no joy!?
Thanks,
Leo
Comments
Comment #2
itmaybejj CreditAttribution: itmaybejj at Princeton University commentedFor what it's worth, I found a way using the existing Tweaks -- perhaps this could be added to the documentation if a direct responsive image filter isn't easy to add?
{{ drupal_entity('media', Media ID, 'Machine name of desired display mode') }}
And a real life example of what it looks like in code with a programmatically determined MID instead of a manually set one:
{{ drupal_entity('media', content.image['#object'].mid.value, 'postcard_tall') }}
Comment #3
Chi CreditAttribution: Chi commented{{ 'public://images/ocean.jpg' | responsive_image_style('narrow') }}
What URL do you expect to be printed here?
Comment #4
lzimmerman CreditAttribution: lzimmerman commentedThis quick patch does the job for me, perhaps it will be helpful as a base.
Currently takes FID and style as parameters, e.g.
{{ node.field_image.0.target_id | image_style_responsive('my_responsive_style') }}
Comment #5
sgalindo2388 CreditAttribution: sgalindo2388 commentedPatch #4 works but might have been created for an older version of the module and it's missing some of the changes from the latest version so I applied the patch to the latest version 1.7 so it applies cleanly.
Comment #6
davidraijmakers CreditAttribution: davidraijmakers commentedI updated the patch to be working with the latest changes in the 8.x-2.x branch
Comment #7
davidraijmakers CreditAttribution: davidraijmakers commentedComment #8
davidraijmakers CreditAttribution: davidraijmakers commentedAdded missing use.
Comment #9
davidraijmakers CreditAttribution: davidraijmakers commentedComment #11
Chi CreditAttribution: Chi commentedAs a workaround you may build
srcset
attribute manually like follows.Comment #12
Chi CreditAttribution: Chi commentedI think converting file ID into markup is not what Twig filter should be used for. This is more a Twig function job. I will try to implement a generic function to render images in Twig templates. That should support responsive image styles as well.
Comment #14
Chi CreditAttribution: Chi commentedI just pushed brand new
drupal_image()
function which supports responsive image styles. Feel free to test it and provide some feedback. The cheat sheet has been updated.Thanks.