0

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?

1 Answer 1

1

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";
Sign up to request clarification or add additional context in comments.

8 Comments

Yes, just realised the error with the " and ', thankyou.
If this cannot work, what would be another way to achieve this?
I updated with a possible way to do it. In the olden days you could use {{ STATIC }} but I didn't find any references to it now...
Hi @thebjorn, I have managed to get the link working: background-image: {% static "5LW/images/slider/6.1.jpg" %}; But I am receiving this error: INVALID PROPERTY VALUE
sounds like you've put the {% static ..%} tag in a file that is not processed by the django template processor, e.g. directly in a .css file?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.