Hi,
I’m iterating through pages in a collection and I want to select from each post, one image and one gif we can find on each folder.
{% for p in page.collection %}
{% set first_image = p.media.images|first %}
{% set first_gif = p.media['avatar.gif'] %}
<h2>{{ p.title }}</h2>
<h3>{{ p.header.headline }}</h3>
{{ first_image }}
{{ first_gif }}
{{ p.summary }}
{% endfor %}
It works with the previous example, but I want to somehow be able to select just one gif image, doesn’t matter what’s the name of it, like I do with images.
I tried with p.media['*.gif'], p.media['*.gif']|first and p.media.animatedImage|first, but nothing, the only way I found yet to select the gifs per page, is by calling it with the exact name of the file, but this is very restrictive for me.
Could you somehow explain a way to have an array with all the “Animated Image” on each page as we do with the images?
give it try with… (replace page with your p variable)
{# get all the images from the page media #}
{% set images = page.media.images %}
{# create an empty array to hold your bg images #}
{% set bg_images = [] %}
{# loop over all the images and put only 'gif' images into the new array #}
{% for filename, image in images %}
{% if filename ends with 'gif' %]
{% set bg_images = bg_images|merge(image) %}
{% endif %}
{% endfor %}
The example comes from this post. There is some more explanation.
Hello mgoll, would you have advice on targeting (for eg.) the second image in the pages media? I see there is “first” and “last”, but I can’t find any examples on knabbing other images in the sequence!
Please be advised that gifs are not ‘images’ but instead ‘animated images’. See Supported Media Files and class AbstractMedia which is returned by page.media in Twig.
This means that the array returned by page.media.images does not contain gif files.
One could get access to all media types included the gifs by using:
page.media['my-animated.gif']
page.media.files, or page.media.all and filter the resulting array on gif extension
The rationale of gifs being excluded from page.media.images is that the image manipulation functions do not work properly on gifs. See this issue at Github.