首页 > 解决方案 > 在 Django 项目的 javascript 文件中包含 javascript 文件

问题描述

我正在使用图表库 apexcharts 并为我在网站的不同部分多次使用的图表定义了一个 javascript 函数。该函数需要一些其他脚本才能工作。所以目前,每次我想使用该函数(位于 util.js 中)时,我都必须在我的 html 模板中导入这样的脚本:

<script type="application/javascript" src="{% static 'shared/js/apexcharts/apexcharts.min.js' %}"></script>
<script type="application/javascript" src="{% static "shared/js/apexcharts/dependency2.js" %}"></script>
<script type="application/javascript" src="{% static "shared/js/apexcharts/dependency1.js" %}"></script>
<script type="application/javascript" src="{% static "shared/js/apexcharts/util.js" %}"></script>

如何在我的 util.js 中包含前 3 个,这样我只需要导入 util.js?

标签: javascriptdjango

解决方案


为了在不重复的情况下导入多个模板的资源,最好有一个父 base.html 来处理它:

base.html:

<html>
  <head>
    <script type="application/javascript" src="{% static 'shared/js/apexcharts/apexcharts.min.js' %}"></script>
    <script type="application/javascript" src="{% static "shared/js/apexcharts/dependency2.js" %}"></script>
    <script type="application/javascript" src="{% static "shared/js/apexcharts/dependency1.js" %}"></script>
    <script type="application/javascript" src="{% static "shared/js/apexcharts/util.js" %}"></script>
  </head>
  <body>
    {% block content %}
     #your other small page here
    {% endblock %}
  </body>
</html>

user_page.html:

{% extends "base.html" %} # extends will add the scripts in header

{% block content %}
   # your content here
{% endblock %}

有关更多信息,您可以在文档中阅读它:https ://docs.djangoproject.com/en/3.1/ref/templates/language/#templates


推荐阅读