What's the best way to get the first image from a collection if you don't know which pages have images? Thanks.
Archive
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.
TWIG
{% 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
TWIG
{% 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:
TWIG
{% 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.
Log in to reply.
Suggested topics
| Topic | Participants | Replies | Views | Activity |
|---|---|---|---|---|
| 0 | 1345 | 9 years ago | ||
| 2 | 932 | 9 years ago | ||
| 2 | 4059 | 9 years ago | ||
| 1 | 2945 | 9 years ago | ||
| 3 | 1117 | 9 years ago |