MarAja
MarAja

Reputation: 1597

Django: Insert image in a template whose path is dynamic

I know I can insert an image in an html generated page based on a template using:

 <img src="{% static "myapp/my_image.jpg" %}" alt="Image Description">

The problem is I want something slightly more complex. Let's say I have an object "user" in my template with a user.first_name and a user.last_name attributes. I would like to insert an image whose path would be:

 <img src="{% static "myapp/{{user.first_name}}_{{user.last_name}}.jpg" %}" alt="Profile Picture">

This line is wrong, I get an error (Django can't parse the expression). Can someone help?

I am building kind of a organization chart with photographs, is that a proper way of including profile pictures for every member (based on the fact that the pictures should be named firstname_lastname.jpg)?

Thanks

Upvotes: 6

Views: 9615

Answers (5)

you can do like this.

<img src ="{% static "folder name"/ %}{{user.first_name}}_{{user.last_name}}.jpg" alt="Profile Picture">

Upvotes: 0

Eswar
Eswar

Reputation: 1212

If the objective is just to set the dynamic image path. This worked for me. You can try this.

{% load static %}
<img src ="{% static 'images/myimage.jpg' %}" alt="My image" width="1500" height="333" id="plot" style="visibility: hidden"/>
<script>
function imageShow(){
  var name="myname";
  {% load static %}
  var filename="{% static 'images/' %}"+name+".png";
  document.getElementById("plot").src=filename;
  document.getElementById("plot").style.visibility='vsible';
}
</script>

Upvotes: 0

Sangat Das
Sangat Das

Reputation: 116

You can do another thing:

<img src ="{% static 'myapp/' %}{{user.first_name}}_{{user.last_name}}.jpg" alt="Profile Picture">

This will work just as fine. Hope this helps :)

Upvotes: 9

Kloudend
Kloudend

Reputation: 161

You'll have to use a custom filter (don't use add, that's not meant for adding strings).

<img src="{% static 'myapp/'|addstring:user.first_name|addstring:'_'|addstring:user.last_name|addstring:'.jpg' %}" alt="Profile Picture">

Where your custom filter addstring could be

# In : templatetags/<app>_extras.py

from django import template

register = template.Library()

@register.filter
def addstring(s1, s2):
    return str(s1) + str(s2)

Another option is having a custom filter do all the magic & use that in img src:

@register.filter
def imgsrc(user):
    return 'myapp/{}_{}.jpg'.format(user.first_name, user.last_name)

Upvotes: 0

rnevius
rnevius

Reputation: 27112

While I recommend creating the path in your view and passing it as context to your template, you can also use the add filter:

{% static "myapp/"|add:user.first_name|add:"_"|add:user.last_name|add:".jpg" %}

You could also create a custom template tag for this. Lots of options.

Upvotes: 6

Related Questions