0

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 :)

2
  • use {% for k, v in dict.items() %} to loop through dictionaries Commented Nov 8, 2018 at 18:06
  • @RockyLi it didnt show up. The img src is still the same. The output is <a class="dropdown-item" data-img="/assets/products/suffix.jpg">Item desc...</a> Commented Nov 8, 2018 at 18:27

2 Answers 2

0

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 %}
Sign up to request clarification or add additional context in comments.

Comments

0

I also found myself facing a similar problem I don't know if its exactly the same; I wanted to link a file in my static folder to my HTML file i.e. src="", the directory should come from a dictionary source. Apparently you could just link it there directly. Here's part of my code ;

{% for dic in posts %}
{% if dic.no == 1 %}
<img alt="" class="u-expanded-width u-image u-image-default src="{% static dic.src %}"><!--/product_image--><!--product_title-->
<h4 class="u-product-control u-text u-text-body-alt-color u-text-2">
<a class="u-product-title-link" href="#"><!--product_title_content-->{{ dic.name }}<!--/product_title_content--></a>
{% endif %}
{% endfor %}

2 Comments

And i could not understand Jeanawhou's answer
You could Just process the path on views and add it to the dictionary to be used in your html code like i did🤷‍♂️.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.