Reputation: 588
Lets say I have an image source as such:
<img src="{% static 'images/category1.png' %}">
This works completely fine - it finds the image and displays it properly. However, its in a for-loop, so I'm going to have different images for each element (in this case, a different image for each category)
For some reason, this doesn't work:
{% for cat in category %}
...
<img src="{% static 'images/{{cat.category_slug}}.png' %}">
...
{% endfor %}
I'm positive that the {{cat.category_slug}} variable has the correct name as my image, as this:
<p>{{cat.category_slug}}</p>
shows 'category1' on my site, which is correct.
Upvotes: 1
Views: 151
Reputation: 476493
You can make use of the |add
template tag [Django-doc] to perform string concatenation:
<img src="{% static 'images/'|add:cat.category_slug|add:'.png' %}">
But it might be more elegant to simply make use of of a method in your Category
model. For example:
class Category(models.Model):
category_slug = models.SlugField(max_length=128)
# …
def get_image(self):
return f'images/{self.category_slug}.png'
then you can implement this as :
<img src="{% static cat.get_image %}">
Upvotes: 1