在Django中,为每个模板加载不同js文件的正确方法是什么?

2024-06-02 06:38:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为每个模板加载不同的.js.css文件(静态文件),但也要为每个模板加载相同的文件组

示例:

first.html-这里我想加载jquery.jsjquery.cssmaps.js

second.html-这里我想加载jquery.jsjquery.css而不加载maps.js

third.html-这里我想加载test.jsmaps.js

现在,我通过{% include 'footer.html' %}将所有文件添加到footer.html.js文件)或header.html.css文件)中,并包括所有这些文件


Tags: 文件test模板示例includehtmljs静态
1条回答
网友
1楼 · 发布于 2024-06-02 06:38:04

您的文件应全部扩展base.html文件:

{% extend base.html %}

然后在base.html中添加所有常用脚本和css。这些将由所有模板继承。还要添加一个空块page_scripts,然后填充各种模板:

<head>
  <link rel="stylesheet" href="{% static 'jquery.css' %}" />
</head>
<body>
  {% block content %}
  {% endblock %}
  <footer>
    <script src="{% static 'jquery.js' %}"></script>
    {% block page_scripts %}{# Specific template scripts here #}{% endblock %}
  </footer>
</body>

最后,在您的子模板中,例如first.html

{% block page_scripts %}
  <script src="{% static 'maps.js' %}"></script>
{% endblock %}

在本例中,jquery.cssjquery.js对于所有模板都是通用的。而maps.js仅加载在您的first.html页面中

相关问题 更多 >