Django 1.5 - How to use variables inside a static tag

Currently, I am transferring all links to static files in my project to the new tag {% static%} introduced by django 1.5, but I have a problem, in some places I use variables to get content. With the new tag I can’t, is there any way to solve this?

Current Code:

<img src="{{ STATIC_URL }}/assets/flags/{{ request.LANGUAGE_CODE }}.gif" alt="{% trans 'Language' %}" title="{% trans 'Language' %}" /> 

What it should be (this does not work):

 <img src="{% static 'assets/flags/{{ request.LANGUAGE_CODE }}.gif' %}" alt="{% trans 'Language' %}" title="{% trans 'Language' %}" /> 
+69
django django-templates django-staticfiles
May 20 '13 at 18:24
source share
4 answers

You must be able to concatenate strings using the add template filter :

 {% with 'assets/flags/'|add:request.LANGUAGE_CODE|add:'.gif' as image_static %} {% static image_static %} {% endwith %} 

What you are trying to do does not work with the static template tag because it only accepts a string or variable:

 {% static "myapp/css/base.css" %} {% static variable_with_path %} {% static "myapp/css/base.css" as admin_base_css %} {% static variable_with_path as varname %} 
+97
May 20 '13 at 18:45
source share

a cleaner way is to set {% static%} as a variable from the beginning of html so we can use it in any way.

 {% load static %} {% static "" as baseUrl %} <img src="{{ baseUrl }}/img/{{p.id}}"></img> 
+17
Mar 03 '15 at 3:37
source share

I got this to work, using an empty string for the static path, and then using my variables in my own section, for example:

 <a href= "{% static "" %}{{obj.a}}/{{obj.b}}/{{obj.c}}.gz" >Name</a> 
+10
Mar 13 '14 at 7:47
source share

@rounin, you can at least use

 {% get_static_prefix %} 

which will be loaded when you {% load static%}. This is more natural than {% static ''%} :)

+10
May 18 '14 at 18:21
source share



All Articles