Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my django project i have to add a prefix into some path defined with %static like this:

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

I have to add the {{ subpath }} value passed from my view, i try this:

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

but the variable was implemented like a text, also i tried:

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

but an error occurred.

How can i add a variable value into my href correctly?

like image 608
Manuel Santi Avatar asked Apr 24 '26 16:04

Manuel Santi


1 Answers

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.

like image 175
Willem Van Onsem Avatar answered Apr 27 '26 21:04

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!