[英]Reference other static file in django javascript file
I need to load a file into a function to use with a telephone autoformatter library ( Intl tel input ) When I tried this in a standalone html page, it worked fine, but when I'm trying to do it in a django project, the file just isn't loading and I think it's because it's not finding where it is in the path. 我需要将文件加载到与电话自动格式化程序库一起使用的函数中( 国际电话输入 ),当我在独立的html页面中尝试此操作时,它工作正常,但是当我尝试在django项目中进行操作时,文件只是没有加载,我认为这是因为找不到路径中的位置。
main.js and utils.js are both in the static directory of my project so I'm not sure why it can't find the utils.js file. main.js和utils.js都在我项目的静态目录中,所以我不确定为什么找不到utils.js文件。
main.js: main.js:
$(document).ready(function() {
$("#phoneNumber").intlTelInput({
utilsScript: "utils.js"
});
});
What I do in cases where I need to reference server-side paths in JavaScript is set up an "app" object in my uppermost template, which I can reference in JavaScript files that are loaded after, typically with require.js. 在需要引用JavaScript中的服务器端路径的情况下,我要做的是在最上面的模板中设置一个“ app”对象,我可以在随后加载的JavaScript文件(通常是require.js)中引用该对象。
Example: 例:
# base.html (upper-most template)
<!DOCTYPE html>{% load static from staticfiles %}
<html>
<head>. . .</head>
<body>
. . .
<script>
var myApp = {
staticUrl: '{{ STATIC_URL }}'
}
</script>
<script src="{% static 'js/some-file.js' %}"></script>
</body>
</html>
# some-file.js
'use strict';
$(document).ready(function(){
console.log(myApp.staticUrl);
});
Look at your URL dispatcher ( urls.py
) to see what the actual path where static files may be requested is. 查看您的URL调度程序(
urls.py
),以了解可能请求静态文件的实际路径是什么。
For example in one of my projects, JavaScript files live at /static/js/
. 例如,在我的一个项目中,JavaScript文件位于
/static/js/
。
So for instance if that were true of your configuration as well, you would do - 因此,举例来说,如果您的配置也是如此,那么您可以-
$(document).ready(function() {
$("#phoneNumber").intlTelInput({
utilsScript: "/static/js/utils.js"
});
});
That's if you want to hard-code the URL. 那就是如果您想对URL进行硬编码。 You can do that in templates, or in .js files which are not processed by the template engine.
您可以在模板或模板引擎未处理的.js文件中执行此操作。
However if you are in a template, I'd recommend using the staticfiles app , specifically the static
template tag which acts as a helper to build paths to your files. 但是,如果您使用的是模板,我建议您使用staticfiles应用程序 ,尤其是使用
static
模板标记,该标记可帮助您建立文件的路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.