2

I had to get rid of the width and height attributes in my images and wanted to learn better the possibilites of Twig in Drupal.

1 Answer 1

0

Copy the image.html.twig file from core/modules/system/templates/ to your theme /templates folder.

If you want to simply hide width and height as image attributes:

{%
set classes = [
    style_name ? 'image-style-' ~ style_name|clean_class,
]
%}
<img{{ attributes|without('width','height').addClass(classes) }} />

If you want to do further things it would be probably better to use template preprocessing functions in the theme file (because of too much logic here) - so this is more a use case for the possibilities in twig files ...

If you want to hide width and height and also want to hide empty class and alt attributes for example:

{%
    set classes = [
        style_name ? 'image-style-' ~ style_name|clean_class,
    ]
%}
{% set printattributes = attributes.addClass(classes)|without('src','alt','class','width','height') %}
{% set printclass = attributes.class.value() ? 'class="' ~ attributes.class ~ '"' : '' %}
{% set printalt = alt ? 'alt="' ~ alt ~ '"' : '' %}


<img {{ printclass|passthrough }} src="{{uri}}" {{ printattributes }} {{ printalt|passthrough }} /> 

This is also very useful in this context: http://drupal.stackexchange.com/questions/137652/override-image-formatter-html-twig/141340#141340

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.