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

Posted by Chris Bartos on April 8, 2016

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.

What do you do after the Official Django Tutorial?

Here's what you'll learn:

  1. Start writing tests
  2. Increase the size / complexity of the Polls application.
  3. Learn how to code in Django by reading the Django source code.
  4. Finding code snippets to use in your website by reading the code of other websites.
  5. Using Javascript in a web app.
  6. Deploying on Heroku and AWS.
We won't send you spam. Unsubscribe at any time. Powered by ConvertKit


Get some value from this post? Please like and share this post because more people also deserve some value. :-)