Search code examples
twiggrav

How to filter image list with twig in grav


I am inserting a list of sponsor images in a sidebar in grav and want to show only images starting with sponsor_.

At the moment, my code adds any image in the page folder.

base.html.twig:

<div class="sidebar-right-content">
<!-- insert R sidebar images here     -->

<div class="sponsor-image">
  <h3>Sponsors</h3>
    {% for image in page.media.images %}
      <br>{{ image.html }}
    {% endfor %}
</div>

I have tried restricting the images returned by using the expression below, but no images are returned:

{% for image in page.media.images if image matches '/^sponsor.*$/' %}

Is there a way to use a filter in this context?


Solution

  • After some testing of a few options, I found a somewhat inelegant way to solve this problem. The main thing to undertand is that page.media.images returns an array, so we can't filter this as a string. So I just nested a match statement. I wonder if there's a one-liner solution.

    {% for image in page.media.images %}
        {% if image.html matches '/.*sponsor.*$/' %}
        <br>{{ image.html }}
        {% endif %}
    {% endfor %}