CoopDaddio
CoopDaddio

Reputation: 627

Adding JavaScript variable to Django static url

I am attempting to add a custom Javascript variable to my Django static url. Unfortunately, the below code is failing.

$(document).ready(function() {
  var randomNum = Math.floor((Math.random() * 12) + 1)
  var text = "{% static '5LW/images/slider/" + randomNum + ".1.jpg' %}"
  document.getElementById("headerImage").style.backgroundImage = url(text)
});

I receive the error:

--

**Error during template rendering**

Could not parse the remainder: ''5LW/images/slider/"' from ''5LW/images/slider/"'

var text = "{% static '5LW/images/slider/" + randomNum + ".1.jpg %}"

--

How would I go about fixing this?

Upvotes: 0

Views: 899

Answers (1)

thebjorn
thebjorn

Reputation: 27360

Your error is because you're mixing " and ' when creating your text variable.

However, this can never work. The {% static ".." %} tag is executed by the server, and your javascript is executed (long after the server has finished processing) by the browser.

You might get this to work by using

var text = "{{ STATIC_URL }}/5LW/images/slider/" + randomNum + ".1.jpg";

(you might have to expose settings.STATIC_URL from your view to your template manually).

.. or perhaps:

var text = "{% static "5LW/images/slider/" %}" + randomNum + ".1.jpg";

Upvotes: 1

Related Questions