Load a static file with a variable name

190 views
Skip to first unread message

I. Dié

unread,
Oct 6, 2015, 1:45:57 PM10/6/15
to Django users
Hi everybody,

I want to load a image with a variable name   in  detail.html like this:

{% load staticfiles %}
<img src="{% static 'pet/images/{{pet.name}}.png' %}" alt={{ pet.name }} />

the image won't load. But when I try this way, it's work perfectly:

{% load staticfiles %}
<img src="{% static 'pet/images/nova.png' %}" alt={{ pet.name }} />

Here is my question How to load a static file with a variable name? Ps: pet.name value is always the image's name for each pet.

best regards

Shawn Milochik

unread,
Oct 6, 2015, 1:51:04 PM10/6/15
to django...@googlegroups.com
Try this:

<img src="{% static 'pet/images/' + {{pet.name}} + '.png' %}" alt={{ pet.name }} />

You're embedding {{pet_name}} in a string. If this was a regular Python statement, it would be like writing "Hello, {0}" and not having a format() at the end.

I. Dié

unread,
Oct 6, 2015, 2:33:36 PM10/6/15
to Django users, Sh...@milochik.com
I tried in your way to concatenate, I don't get any exception, but  the image image does'nt want to display. The plage only throw the "alt" value. Even for this line of code it's thing.

François Schiettecatte

unread,
Oct 6, 2015, 2:40:01 PM10/6/15
to django...@googlegroups.com
The '+' is an error, the line look more like this:

<img src="{% static 'pet/images/' %}{{pet.name}}.png" alt={{ pet.name }} />

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f29da80b-ffe4-421c-9aba-8ad76b87a484%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

I. Dié

unread,
Oct 7, 2015, 9:55:32 AM10/7/15
to Django users
Thank you very much monsieur François

Simon Charette

unread,
Oct 7, 2015, 5:35:14 PM10/7/15
to Django users
You'll want to use

<img src="{% static 'pet/images/'|add:pet.name|add:'.png' %}" alt={{ pet.name }} />

Because François' suggestion will break if you use a static file storage that doesn't
allow missing files reference such as the ManifestStaticFilesStorage.

Simon
Reply all
Reply to author
Forward
0 new messages