Variables in Django Static Tags

The Django staticfiles app is great for getting your static files working both in development in production. One feature the documentation is not clear on is the use of context variables inside static tags. Lets say you have a context variable named “MY_PROJECT” and you try to do the following in a template:

{% load staticfiles %}
<link href="{% static 'css/{{ MY_PROJECT }}.css' %}" rel="stylesheet">

This works when DEBUG=True, but causes mysterious HTTP 500 errors when DEBUG=False.

The way to accomplish this is to make a new context variable in your views (or context processor), like:

MY_PROJECT_CSS = 'css/{}.css'.format(MY_PROJECT)

Then change your template to:

{% load staticfiles %}
 <link href="{% static MY_PROJECT_CSS|safe %}" rel="stylesheet">

Don’t forget the |safe filter, or you will get some strange errors.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s