Django:在模板内导入javascript不起作用

时间:2018-11-05 15:47:01

标签: javascript django django-templates

我正面临着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...")
    }

新的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

我一定做错了什么,您有解决这个问题的提示吗?

1 个答案:

答案 0 :(得分: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>

如果静态变量定义明确,则应该可以使用。

相关问题