简体   繁体   中英

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?

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM