Reputation: 1442
So I have my views.py in Django which is rendering a list of objects to my html template. Everything is working fine. Now, the objects have some object ID associated to them. And I have named the images in the 'static/images/' directory the same as the object ID.
So image 1.jpg will correspond to object with object id = 1, 2.jpg for object id = 2 and so on.
Now i want to load image in my img tag in my html, but the src URL of the img tag will depend on the object id.
Following is my html template:
{% for result in results %}
<li class="card" id="card">
<tr>
<td>
<div class="card-image-container" id="card-image-container">
<img class="card-image" id="card-image" data-card-id="{{result.id}}" src="{% static 'images/{{ result.id}}.jpg' %}">
</div>
</td>
<td>
<div class="card-info-container" id="card-info-container">
<p> {{ result.card_name }} </p>
</div>
</td>
</tr>
</li>
{% endfor %}
The above is not working as the html is not able to parse {{result.id}}. If i hard code the value of url say like this:
src="{% static 'images/1.jpg' %}"
then the above successfully loads the 1.jpg for all the li elements, but what i want is the url to be formed according to the {{result.id}} value.
I've tried using the solution given in the following links, but none worked for me.
Links -> Reference template variable within Jinja expression
Variable within filename in jinja2
Variable in Flask static files routing [url_for('static', filename='')]
Any help will be appreciated.
Upvotes: 0
Views: 1059
Reputation: 4068
You can use get_static_prefix
(documentation):
{% load static %}
<img class="card-image" id="card-image" data-card-id="{{result.id}}" src="{% get_static_prefix %}images/{{ result.id}}.jpg">
Upvotes: 1