【问题标题】:Reference other static file in django javascript file在 django javascript 文件中引用其他静态文件
【发布时间】:2015-08-17 00:38:50
【问题描述】:

我需要将文件加载到函数中以与电话自动格式化程序库一起使用 (Intl tel input) 当我在独立的 html 页面中尝试此操作时,它运行良好,但是当我尝试在 django 项目中执行此操作时,文件只是没有加载,我认为这是因为它没有找到它在路径中的位置。

main.js 和 utils.js 都在我项目的静态目录中,所以我不确定为什么它找不到 utils.js 文件。

main.js:

$(document).ready(function() {
    $("#phoneNumber").intlTelInput({
        utilsScript: "utils.js"
    });
});

【问题讨论】:

  • 看看this这个例子是否适合你。
  • 您也可以尝试this 选项。除了{% static 'your_js_here.js' %}
  • @DejaVu 在第一个例子中,它怎么知道upload_pathuploadify_path是什么?
  • 您在视图中呈现变量,例如context = {'upload_path': upload_path, 'uploadify_path': uploadify_path}return render(request, 'template_name.html', context)。如果你从你的 js 文件中创建了 html,你可以扩展一个你想注入你的 js 的 html - 见{% extends %}
  • 不幸的是,我目前没有机会对此进行测试,也不确定它是否正确修复,但它应该可以工作。如果它不考虑寻址到 IRC 上的 django 频道。

标签: javascript jquery django upload


【解决方案1】:

如果我需要在 JavaScript 中引用服务器端路径,我会在最上面的模板中设置一个“app”对象,我可以在之后加载的 JavaScript 文件中引用它,通常使用 require.js。

例子:

# 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);
});

【讨论】:

    【解决方案2】:

    查看您的 URL 调度程序 (urls.py) 以了解可能请求静态文件的实际路径是什么。

    例如,在我的一个项目中,JavaScript 文件位于 /static/js/

    例如,如果您的配置也是如此,您会这样做 -

    $(document).ready(function() {
        $("#phoneNumber").intlTelInput({
            utilsScript: "/static/js/utils.js"
        });
    });
    

    如果您想对 URL 进行硬编码。您可以在模板中执行此操作,或者在模板引擎未处理的 .js 文件中执行此操作。

    但是,如果您在模板中,我建议您使用 staticfiles app,特别是 static 模板标签,它充当帮助构建文件路径的工具。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      • 2015-08-28
      • 2019-03-05
      • 2017-12-22
      • 2012-12-10
      • 2018-02-01
      • 2012-02-28
      相关资源
      最近更新 更多