Get the image path from uploaded file (JSON Flex Objects)


I’m playing with Flex Objects and I’ve just created one for authors or contributors in a web. I export each author to .json file in user/data/flex-objects/. Each author has an avatar image too (it is storaged in user/data/flex-objects/avatars).

The avatar image is uploaded from Flex form with a File blueprint. I get all values from Json correctly, except avatar image. This is my code:

{% set flex = grav.get('flex_objects') %}
{% set authors ='authors') %}  
{% set collection = authors.getCollection() %}

        {% for author in collection %}
            {% if author.avatar %}
            <img src="{{ author.avatar.path|e }}" alt="{{ author.authorname }}" />
            {% endif %}
            Name: {{ author.authorname }} <br>
            Biography: {{ author.biography }} <br>
            Tags: {% for tag in author.tags %} {{ tag|raw }}{% if not loop.last %}, {% endif %}{% endfor %}
        {% endfor %}

How can I get the avatar image path correctly.

Thanks in advance.

I think the absolute_url filter could be useful in your case Twig Filters | Grav Documentation.

<img src="{{ author.avatar.path|absolute_url }}" ... />

In case it doesn’t work, there is a url function you can use in your twig template:

<img src="{{ url(author.avatar.path) }}" ... />

But I can’t find it in the documentation right now… I hope it helps :sweat_smile:

This solution doesn’t work. Actually it was my first option.

I’ve found a solution that works, at the moment, but I don’t know if it is the better.

{% if author.avatar %}
            <div class="align-center">
                {# assign the uploaded file name to a variable #}
                {% set avatar_image = author.avatar|first %}
                {# append the filename to the intended source url #}
                {% set avatar_url = url(avatar_image.path) %}
                <img class="image fit" src="{{ avatar_url }}" title="" alt="">
 {% endif %}

BTW, thanks @CuriousCI for your answer.

It is really complicated work in twig templates with uploaded files with filepicker.

I wonder if it will only work because of the |first filter. I haven’t tried it without that filter yet.

1 Like

My bad, I totally forgot that when you have flex-objects with files in them, those files are stored as an array of files in the object (even if it’s just one).

I just tried using {{ object.file|first.path|absolute_url }} in one of my projects, and it works.

<img src="{{ author.avatar|first.path|absolute_url }}" ... />

So this could probably work for you, without having to create temporary variables. In any case, when you have a file in your flex object, it’s always stored as an array inside the object, so that |first is mandatory, unless you iterate with a for:

{% for avatar in author.avatar %}
    <img src="{{ avatar.path|absolute_url }}">
{% endfor %}