How do I load an image from a variable in Twig? (With AsseticBundler)

1.5k Views Asked by At

I am trying to loop through an array with strings and use those strings in my image source path. That way I can display a different image for every loop.

This is a piece of code that works, but only with a set string, which means I can't make this all too dynamic this way:

{% image 'img/appel ijs.jpg' %}
    <img class="recept-image-custom" src="{{ asset_url }}"/>
{% endimage %}

This is what I have tried:

{% for item in items %}
    <tr>
        <td scope="col">
            {% image ('img/' ~ item.name ~ '.jpg') %}
                <img class="recept-image-custom" src="{{ asset_url }}"/>
            {% endimage %}
        <td>
    </tr>
{% endfor %}

When I do this I get the following error: Unexpected token "punctuation" of value "("

Beware that I am still quite new to twig so excuse me if this is completely wrong. I already have tried asset(''), but this way I can not access my web folder when I run the server.

1

There are 1 best solutions below

1
stephan.mada On

How about this :

{% for item in items %}
    <tr>
        <td scope="col">
            <img class="recept-image-custom" src="{{ asset('img/' ~ item.name ~ '.jpg') }}"/>
        <td>
    </tr>
{% endfor %}