Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django {% static 'path' %} in javascript file

Tags:

django

In my script.js:

pic.src = "/static/photos/1.jpg"; // This works pic2.src = "{% static 'photos/1.jpg' %}" // Does not work 

Why in the world this happens? Since in my home.html, the {% static 'path' %} works:

{% load staticfiles %} <script src="{% static 'script.js' %}"></script>  // This works 

And is it {% load staticfiles %} or {% load static %} ? Both work for me, script.js is loaded.

like image 981
lucahuy Avatar asked Jan 13 '15 22:01

lucahuy


People also ask

What is {% load static %} in Django?

The {% static %} template tag generates the absolute URL of static files. That's all you need to do for development. Reload http://localhost:8000/polls/ and you should see that the question links are green (Django style!) which means that your stylesheet was properly loaded.


Video Answer


2 Answers

Since you are using django's template language you can ONLY do this within your template between <script> tags. In other words if you wished to use your pic2.src javascript variable in an external script then you would need to declare it between <script> tags like so

<script>     var pic2.src = "{% static "photos/1.jpg" %}" </script> 

And then you could access it in your external scripts that you might load like this:

<script type="text/javascript" src="{% static "js/my_external_script.js" %}"></script> 

Regarding your question concerning load static and load staticfiles there is little distinction. Both act as a joiner for the STATIC_URL in your settings.py and the actual path to the file itself so both should work for your case. See here and here for more info.

like image 104
alacy Avatar answered Oct 02 '22 11:10

alacy


If you need many static (or media) url's in your .js files, this might be more convenient:

<script>     var static_url = "{% get_static_prefix %}";     var media_url = "{% get_media_prefix %}"; </script> 

Then both url's are freely available in all javascript files.

like image 33
knbk Avatar answered Oct 02 '22 10:10

knbk