Twig and media paths

Hi,
i’m trying to get image url from twig template. As the page Where to put your media files explains, in my twig template i put
{% set image_url = page.find('/images').media['myphoto.jpg'] %}
and in user/pages/images i put the image myphoto.jpg, but image_url is blank! What am i doing wrong??

Also in twig you can’t use streams like:
ìmage://myphoto.jpg?
Grav is claiming unexpected punctuation if i put in {{}} and unexpected tag if i put in {%%}

Mmm testing with normal pages works, but i’m using modular pages, maybe this is the problem…

You have set image_url to the media object rather than its location. Media objects have a url method, so you can use page.find('/images').media['myphoto.jpg'].url. Close!

There are other ways too.

You can use the Grav Twig url function, which supports streams: {{ url('ìmage://myphoto.jpg') }}. Otherwise the syntax is invalid Twig, why you are seeing those messages.

Many thanks!! All suggested works, but why
page.media['myphoto.jpg'].url
does not?
(This is a modular page)
myphoto.jpg is inside:
01.modular/_mymodularpage/
01.modular/images
user/pages/images

Answering myself, because averytime i add an image you have to clear the f…ing cache!!! :face_with_symbols_over_mouth:

I recommend setting up an environment more suitable for developing and debugging. Cache behaviour can be tweaked per environment. It’s also easier to find out what’s going on using the debug toolbar.

Hope that helps reduce some of the frustrations.

1 Like