Django {%static'path'%}在javascript文件中 [英] Django {% static 'path' %} in javascript file

查看:1119
本文介绍了Django {%static'path'%}在javascript文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的script.js中:

In my script.js:

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

为什么在世界上发生这种情况?因为在我的home.html中,{%static'path'%}起作用:

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

是否是{%load staticfiles%}或{%load static%}?两者都适用于我,script.js被加载。

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

推荐答案

由于您使用django的模板语言,您只能 / strong>在< script> 标签之间的模板中执行此操作。换句话说,如果您希望在外部脚本中使用您的 pic2.src JavaScript变量,那么您需要在< script> 像这样的标签

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>

有关加载静态 load staticfiles 几乎没有区别。两者都作为您的 settings.py 中的 STATIC_URL 的连接器以及文件本身的实际路径,因此应该为你的案件工作请参阅此处这里了解更多信息。

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.

这篇关于Django {%static'path'%}在javascript文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆