Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...