最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

theme development - Timber: Get single image from media library with all attributes

programmeradmin0浏览0评论

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=".png" alt="This is the image!" srcset=".png 1052w, .png 150w, /[email protected] 300w, .png 768w, .png 1024w, /[email protected] 600w" sizes="(max-width: 1052px) 100vw, 1052px">

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/wp-content/uploads/2019/11/myimage.png" alt="This is the image!" srcset="https://mywebsite/wp-content/uploads/2019/11/myimage.png 1052w, https://mywebsite/wp-content/uploads/2019/11/myimage-150x150.png 150w, https://mywebsite/wp-content/uploads/2019/11/[email protected] 300w, https://mywebsite/wp-content/uploads/2019/11/myimage-768x768.png 768w, https://mywebsite/wp-content/uploads/2019/11/myimage-1024x1024.png 1024w, https://mywebsite/wp-content/uploads/2019/11/[email protected] 600w" sizes="(max-width: 1052px) 100vw, 1052px">
Share Improve this question asked Nov 9, 2019 at 19:04 KalnodeKalnode 2261 silver badge11 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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

发布评论

评论列表(0)

  1. 暂无评论