If file added to page, is it possible to filter by type?

I’m selecting the first image attached to a post and using it in an img tag within my Twig template, like so:
<img src="{{ p.media.images|first.cropZoom(1200, 500).url }}"/>

If this is an SVG, then instead of .images, I would use .files, like so:
<img src="{{ p.media.files|first.cropZoom(1200, 500).url }}"/>

I’m trying to find a way so that if the first image is a real image file (.jpg, .gif), then do the first, but if the first image is an .svg, then to do the second… How can I ‘filter’ the second so that it would only show an SVG, and not say a PDF, or anything else that might be uploaded?

I’ve searched and cannot find anything to help me do that, and I don’t see anything in the Twig documentation that might help either…

Can anyone shed some light on how this might be achieved please?

@col You could query the properties of page.media.images|first, like

{% if page.media.images|first.mime == "image/jpeg" %} 
or
{% if page.media.images|first.type == "image" %} 
or
{% if page.media.images|first.extension == "jpg" %}

If you switch on the debugger and dump the file, you will see its properties:

{{ dump(page.media.images|first) %}
2 Likes

Brilliant, thanks @pamtbaau! That seems exactly what I’ll need. I had no idea those properties even existed! Would you also know if there is a reference of which are available?

I’ve used @pamtbaau’s suggestion like so, to achieve what I needed…

{% if p.media|first.extension == "svg" %} <img src="{{ p.media.files|first.url }}"/> {% elseif p.media|first.extension == "jpg" or p.media|first.extension == "gif" or p.media|first.extension == "png" %} <img src="{{ p.media.images|first.cropZoom(1200, 500).url }}"/> {% endif %}

1 Like

@col, I hope you don’t mind me playing with your solution a bit… The following piece of code feels a bit more elegant. To me at least…

In file /system/config/media.yaml you can see for each file which “type” is assigned by Grav.

{% set firstImage = (page.media|first) %}

{% if firstImage.type == "vector" %}
    <img src="{{ firstImage.url }}"/>
{% elseif firstImage.type == "image" %}
    <img src="{{ firstImage.cropZoom(1200, 500).url }}"/>
{% endif %}
2 Likes

Of course not @pamtbaau, I agree that my ‘solution’ wasn’t the most elegant. :ok_hand:

Thanks once again!