【问题标题】:Django : Import javascript inside a template doesn't workDjango:在模板中导入 javascript 不起作用
【发布时间】:2019-04-09 00:06:48
【问题描述】:

我正面临 django 的一个新问题。我正在开发一个网站(所以我不在生产步骤中)并且我想在我的模板中使用 javascript。

当我直接在我的模板上编写脚本并将其链接到一个按钮时,脚本可以正常工作。但是当我想从 .js 文件中导入它时,它不再起作用了。

我的静态目录似乎工作正常,我可以从中导入 css 甚至图像。

这是我的文件:

base.html:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        {% load static %}

        <title>Title</title>
        <link rel="stylesheet" href="{% static 'webcalendar/css/bootstrap.css' %}">
        <link rel="stylesheet" href="{% static 'webcalendar/css/style.css' %}">

        {% block script %}  {% endblock %}
    </head>

    <body>

        {% block content %}  {% endblock %}

    </body>
</html>

fonction_test.html : 脚本直接写在模板中的地方

{% extends 'webcalendar/base.html' %}

{% block script %}

    <script type="text/javascript">

        function printInConsole(){
                console.log("PRINTING...")
        }

    </script>

{% endblock %}

{% block content %}

    <button  onclick="printInConsole()" class="btn btn-warning">Print in console</button>

{% endblock %}

所以前一个正在工作

但是,如果我尝试从应用程序的静态文件夹中的 .js 文件导入脚本,它将不起作用。

calendar.js:

function printInConsole(){
            console.log("PRINTING...")
    }

new fonction_test.html : 我尝试从 .js 导入脚本

{% extends 'webcalendar/base.html' %}
{% load static %}

{% block script %}

    <script type="text/javascript" scr="{% static 'webcalendar/js/calendar.js' %}"></script>

{% endblock %}

{% block content %}

    <button  onclick="printInConsole()" class="btn btn-warning">Print in console</button>

{% endblock %}

我收到以下错误:

ReferenceError: printInConsole is not defined

我一定是做错了什么,你有什么解决办法吗?

【问题讨论】:

  • 你能试试这样的路径吗:&lt;script src="path_to_your_static/static/webcalendar/js/calendar.js"&gt;&lt;/script&gt;。然后它似乎不起作用,因为您写道:scr 而不是src

标签: javascript django django-templates


【解决方案1】:

在我看来,您的问题来自您的语法:

<script type="text/javascript" scr="{% static 'webcalendar/js/calendar.js' %}"></script>

请将scr="" 更改为src="

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

如果你的静态是明确定义的,它应该可以工作。

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 2015-06-20
    • 2020-01-15
    • 2022-01-05
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多