1

In my Timber-based theme, I'm getting a single image from the media library using the following (based on Timber/Image):

<img src="{{ Image(678).src }}" alt="{{ Image(678).alt }}" srcset="{{ Image(678).srcset }}" sizes="{{ Image(678).img_sizes }}" />

However it's silly to repeatedly state the image id for each attribute.

Is there a single command that can spit out a fully populated image instance or does this call for a custom PHP function, and make it available to Timber?


For reference, the above code outputs this:

<img src="https://mywebsite.com/wp-content/uploads/2019/11/myimage.png" alt="This is the image!" srcset="https://mywebsite.com/wp-content/uploads/2019/11/myimage.png 1052w, https://mywebsite.com/wp-content/uploads/2019/11/myimage-150x150.png 150w, https://mywebsite.com/wp-content/uploads/2019/11/[email protected] 300w, https://mywebsite.com/wp-content/uploads/2019/11/myimage-768x768.png 768w, https://mywebsite.com/wp-content/uploads/2019/11/myimage-1024x1024.png 1024w, https://mywebsite.com/wp-content/uploads/2019/11/[email protected] 600w" sizes="(max-width: 1052px) 100vw, 1052px">

1 Answer 1

0

Ok, it's as simple as:

{% set post_image = Image(678) %}
<img src="{{ post_image.src }}" alt="{{ post_image.alt }}" srcset="{{ post_image.srcset }}" sizes="{{ post_image.img_sizes }}" />

Ref: Twig set

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.