Skip to content
● Grav 2.2 is out: 2x faster cold starts and 96% less memory on big sites. Read the announcement →

Best way to get first image from collection

Started by Muut Archive 11 years ago · 6 replies · 2510 views
11 years ago

What's the best way to get the first image from a collection if you don't know which pages have images? Thanks.

11 years ago

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 %}
11 years ago

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 %}

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 2575 9 years ago
Archive · by Muut Archive, 9 years ago
2 1695 9 years ago
Archive · by Muut Archive, 9 years ago
2 4986 9 years ago
Archive · by Muut Archive, 9 years ago
1 3814 9 years ago
Archive · by Muut Archive, 9 years ago
3 1803 9 years ago