Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Best way to get first image from collection

Started by Muut Archive 11 years ago · 6 replies · 2359 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 1344 9 years ago
Archive · by Muut Archive, 9 years ago
2 930 9 years ago
Archive · by Muut Archive, 9 years ago
2 4058 9 years ago
Archive · by Muut Archive, 9 years ago
1 2943 9 years ago
Archive · by Muut Archive, 9 years ago
3 1116 9 years ago