Skip to content

Instantly share code, notes, and snippets.

@sachbearbeiter
Last active September 27, 2021 09:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sachbearbeiter/2aa50fbc3349e32c7957 to your computer and use it in GitHub Desktop.
Save sachbearbeiter/2aa50fbc3349e32c7957 to your computer and use it in GitHub Desktop.
D8: Theming examples: Images: How to print individual image values and suppress width and height via the image.html.twig template ... *First results of struggling through Drupal 8 - better solutions are probably out there! **Drupal 8 is still Beta - improvements through API modifications are possible!
{#
/**
* @file
* Default theme implementation of an image.
*
* Available variables:
* - attributes: HTML attributes for the img tag.
* - style_name: (optional) The name of the image style applied.
*
* @see template_preprocess_image()
*
* @ingroup themeable
*/
#}
{# ORIG #}
{%
set classes = [
style_name ? 'image-style-' ~ style_name|clean_class,
]
%}
<img{{ attributes.addClass(classes) }} />
{# VALUES #}
{{ attributes.src }} {# absolute image path considering the image style #}
{{ attributes.width }}
{{ attributes.height }}
{{ attributes.alt }}
{{ attributes.class }}
{{ uri }} {# absolute image path considering the image style #}
{{ width }}
{{ height }}
{{ alt }}
{# COMPOSED EXAMPLE - cleaner would be template_preprocess_image() #}
{%
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 }} />
@matthodgson
Copy link

Thanks for this @sachbearbeiter. I've been bashing my head against the key board for hours. This totally solved my issue of needing an absolute url in images for an email template

@sachbearbeiter
Copy link
Author

Thanks for the feedback ...
And it's still working - fine ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment