Search code examples
pythondjango-templatesdjango-viewsdjango-staticfiles

How to use dictionary variables inside django static tag


I am trying to concatenate a Django variable to an img src. I have found a solution to do it but still when I inspect the browser, the value doesn't show up. By the way the value that I am calling is dict type which looks like this >>> djangoDict output: {<foreignModel: ModelValue>: <Product: Item Desc...}

I was able to show the ModelValue using the 2 curly braces {{ djangoDict }} but I can't do it when concatenating with an address.

So here my code:

{% for dd in djangoDict %}
            {% with 'products/anotherFolder/'|add:dd|add:'/suffix.jpg' as myImg %}
              <a class="dropdown-item" data-img="{% static myImg %}">{{ dd }}</a>
            {% endwith %}
{% endfor %

This is what I get when inspecting element:

<a class="dropdown-item" data-img="/assets/suffix.jpg">ModelValue</a>

What I want to show up:

<a class="dropdown-item" data-img="/assets/products/anotherFolder/ModelValue/suffix.jpg">ModelValue</a>

Thank you so much for anyone that would help :)


Solution

  • I saw a similar problem to mine which solves my issues on concatenating image path. It is the best answer to my question.

    I used STATIC_URL which is configured on settings.py

    My code now looks like this:

    {% for dd in djangoDict %}
        <a class="dropdown-item" data-img="{{ STATIC_URL }}products/anotherFolder/{{ dd }}/suffix.jpg">{{ dd }}</a>
    {% endfor %}