【问题标题】:Django JavaScript tag at the end of a base.html file structurebase.html 文件结构末尾的 Django JavaScript 标记
【发布时间】:2021-01-26 11:33:51
【问题描述】:
我正在使用 Django 开发一个网站。我使用 Template Inheritance 是为了不在几个 html 子文件中重复代码(例如导航栏)。我不想重写的部分代码是我嵌入 JavaScript 的地方:
<script src="whatever"></script>
众所周知,这段代码最好放在 .html 文件中的正文末尾,因为这样可以避免锁定其他资源而无法更快地下载。
所以我的问题是:我应该如何告诉我的 base.html 模板脚本代码应在每个子 html 文件中的正文末尾?
【问题讨论】:
标签:
javascript
css
django
inheritance
【解决方案1】:
Base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block main_body_data %}
{% endblock %}
{% block child_js_above_files %}
{% endblock %}
<script src="whatever"></script>
{% block child_js_below_files %}
{% endblock %}
</body>
</html>
child.html:
<!DOCTYPE html>
{% extends "base.html" %}
{% block title %}
Home page
{% endblock %}
{% block main_body_data %}
<h1>main content</h1>
{% endblock %}
{% block child_js_above_files %}
<script src="whateverabove"></script>
{% endblock %}
{% block child_js_below_files %}
<script src="whateverbelow"></script>
{% endblock %}
【解决方案2】:
您可以简单地为基本模板创建一个base.html 文件。
它应该看起来像,
base.html
<!Doctype HTML>
...
<head>
...
{% block head %}
{% endblock head %}
</head>
<body>
{% block content %}
{% endblock content %}
<!-- page specific script tag here -->
{% block script %}
{% endblock script %}
<!-- common script tag for whole site (will be loaded at last) -->
<script src="whatever"></script>
...
</body>
</html>
【解决方案3】:
在base.html的末尾创建一个块
{% block js_files %} {% endblock %}
然后在需要时覆盖它。