[Django]-Django add a variable value into {%static 'path' %}

3👍

You can perform the string concatenation with the add [Django-doc] template filter tag:

<link rel="stylesheet" href="{% static subpath|add:"/css/animate.css" %}">

For example:

>>> from django.template import Template, Context
>>> Template('{% load static %}{% static subpath|add:"/css/animate.css" %}').render(Context({'subpath': 'foobar'}))
'/static/foobar/css/animate.css'

As you can see the subpath variable is associated with the 'foobar'. So in the {% static .. %}, tag we construct with subpath|add:"/css/animate.css" a new string foobar/css/animate.css. By using the {% static .. %} tag, this will be replaced (here, according to default settings), with /static/foobar/css/animate.css.

Leave a comment