What’s the best way to get the first image from a collection if you don’t know which pages have images? Thanks.
Antimatter has an example of this type of logic: https://github.com/getgrav/grav-theme-antimatter/blob/develop/templates/blog.html.twig#L6-L12
Thanks for the example. I tried accessing posts.media
, but it’s always null. Here’s how I can get the first post’s image url like in antimatter, but I’d like to be able to get the first image regardless of what post it’s in.
{% set posts = taxonomy.findTaxonomy($filter) %}
{% if posts.count > 0 %}
{% set thumbUrl = theme_url ~ '/images/default.png' %}
{% if posts|first.media.images %}
{% set thumbUrl = posts|first.media.images|first.url %}
{% endif %}
…
{% endif %}
Something like
{% for post in posts %}
{% if post.media.images %}
{% set thumbUrl = post.media.images|first.url %}
{% endif %}
{% endfor %}
unfortunately twig cannot break in a loop, but maybe this can be used http://twig.sensiolabs.org/doc/tags/for.html#adding-a-condition
This seems to work and stops iteration as soon as it finds an image:
{% set thumbUrl = url('theme://images/thumb.jpg') %}
{% set break = false %}
{% for post in posts if not break and post.media.images %}
{% set thumbUrl = post.media.images|first.url %}
{% set break = true %}
{% endfor %}
Is your last example working for you?
Yes.