Use a Template Filter to Nest a Context Variable Inside of a staticfile Template Tag

You have a variable in a template that holds a filename. Then, you want to pass the variable to your template so that you can put the filename in an <img> tag and render it from staticfiles.

You try doing something like this:

<img src="{% static 'mysite/{{filename}}' %}" width="100" height="100" />

However, this doesn’t work at all! What do you do? You know that the variable holds the filename. You take out the static tag and just try:

<p>{{filename}}</p>

This prints the filename that you expect. What are you doing wrong? Is there a way I can get around this? The first thing that is important to remember is that you aren’t able to nest a template tag inside of any other tag inside of a Django template.

Here’s an important tip: If there is something inside a template that doesn’t seem to work the way you expect it work, the first thing you should check is to see if there is a ‘filter’ that will do what it is that you want.

Use the “add” Filter

Here is a list of Built-in template tags and filters. Anytime you need to figure out to get something working in your template, you should always use that page. Look there first!

The add filter will concatenate strings or it will add together numbers. One thing you have to be careful about however, is that if strings can be coerced into numbers, for example:

<p>{{value | add:"2"}}</p>

This example will first coerce the string: “2” into the integer 2 and add it to whatever is stored in the variable value.

However, if the strings cannot be coerced into integers, and they are both strings, they will be concatenated. Here is an example of concatenating the STATIC_URL with your context variable:

<p>{% static 'mysite/' | add:filename %}</p>

If the filename variable is “file.jpg” then the template would be rendered as:

<p>static/mysite/file.jpg</p>

Of course, this depends on your STATIC_URL but the concept works.

Struggle with the Django Documentation?

If this post helped you, sign up for my newsletter and you'll get a new post each week that will help you master Django ABSOLUTELY FREE!

Powered by ConvertKit