[Fixed]-Load static file with variable name in django


Too many quotes!


<a href="{% static 'images/{{ image.title }}.png' %}">img file</a> 

and you don’t have to call the static in the link because you already load the static


You should pass a full string to the static tag from staticfiles. This is so it can use your staticstorages to find your file.

{% load staticfiles %}
{% with 'images/'|add:image.title|add:'.png' as image_static %}
  {% static image_static %}
{% endwith %}

But in your use case it might be better if you just store the path of the images on the image model itself.



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

<a href= "{% static "" %}{{obj.a}}/{{obj.b}}/{{obj.c}}.gz" >Name</a>


You can use get_static_prefix template tag. get_static_prefix is a variable that contains the path specified in your STATIC_URL. Your code would be:

{% load static %}
<a href="{% get_static_prefix %}static/images/{{ image.title }}.png">img file</a>


{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
<a href="{{ STATIC_PREFIX }}static/images/{{ image.title }}.png">img file</a>

Reference: get_static_prefix


You should avoid nesting tags.

What are you trying to solve? Isn’t the image part of dynamic content? The static tag is for static content not uploaded media files.

If you must use the static tag the correct way would be something in the order of;

{% static image %} or {% static image.file %}

Depending on the object layout. If you’re using an ImageField (inherits FileField) the image object already holds the path, so there’s no need to manually add extensions.


What I ended up doing was to just split the path from the name itself. Those images represents tabs, are static and in a sequence. They are not connected to the database imagewise.

I didn´t want to repeat the html for every run so I ended up doing a forloop like this, a bit simplified.

{% for option in options_obj %}
   <img class="highlight" src="{% static "store/img/editor/tab-" %}
   {{ option.name.lower }}-selected.png">
{% endfor %}

Even though this does work in most situations it can really mess stuff up as well. For me this occured when having different images for different language settings and at the same time using tools like CachedStaticFilesStorage. If you need to add language code or something else to your image this is a more solid solution

{% for option in options_obj %}
    <img class="highlight" src="{% static "store/img/editor/tab-"
    |add:LANGUAGE_CODE|add:"-selected.png" %}">
{% endfor %}

Leave a comment