在块外部或内部写入脚本标签?

Ati*_*ooq 3 python django django-templates

请考虑以下代码片段。

<!--templates/home.html-->
{% extends 'base.html' %}
{% load static %}

{% block content %}
  {% for post in object_list %}
  <div class = 'post-entry'>
    <h2><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</h2>
      <p>{{ post.body }}</p>
  </div>
  {% endfor %}
  <script type = "text/javascript" src = "{% static 'js/test.js' %}"></script>
{% endblock content %}
Run Code Online (Sandbox Code Playgroud)

<!--templates/home.html-->
{% extends 'base.html' %}
{% load static %}

{% block content %}
  {% for post in object_list %}
  <div class = 'post-entry'>
    <h2><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</h2>
      <p>{{ post.body }}</p>
  </div>
  {% endfor %}
{% endblock content %}
<script type = "text/javascript" src = "{% static 'js/test.js' %}"></script>
Run Code Online (Sandbox Code Playgroud)

第一个执行成功,但第二个没有执行。是否有必要从 django 模板块内部加载外部静态文件,如果没有那么为什么第二个代码不执行?

PS:我是 django 的新手。

为了清楚起见,我还在此处提供基本模板的代码。

<!--templates/base.html-->
{% load static %}
<html>
  <head><title>Django Blog</title>
    <link href = "{% static 'css/base.css' %}" rel = "stylesheet">
  </head>
  <body>
    <header><h1><a href = "{% url 'home' %}">Django Blog</a></h1></header>
    <div>
      {% block content %}
      {% endblock content %}
    </div>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 5

\n

第一个执行成功,但第二个没有执行。是否有必要从 django 模板块内部加载外部静态文件,如果没有那么为什么第二个代码不执行?

\n
\n\n

如果您覆盖基本模板,那么您只能“填充块”。Django 应该在哪里编写您在块之外编写的内容?在文件的开头?在文件末尾?中间某个地方?

\n\n

正如有关模板继承的文档 [Django-doc]中所指定的:

\n\n
\n

Django\xe2\x80\x99s 模板引擎中最强大的 \xe2\x80\x93 以及最复杂的 \xe2\x80\x93 部分是模板继承。模板继承允许您构建基本 \xe2\x80\x9csculpture\xe2\x80\x9d 模板,其中包含站点的所有常见元素并定义子模板可以覆盖的块

\n
\n\n

但是,您可以定义多个块。例如,通常在末尾添加一个块,您可以选择在其中添加一些额外的 JavaScript,例如:

\n\n
<!--templates/base.html-->\n{% load static %}\n<html>\n  <head><title>Django Blog</title>\n    <link href="{% static \'css/base.css\' %}" rel="stylesheet">\n  </head>\n  <body>\n    <header><h1><a href="{% url \'home\' %}">Django Blog</a></h1></header>\n    <div>\n      {% block content %}\n      {% endblock content %}\n    </div>\n  {% block js %}\n  {% endblock %}\n  </body>\n</html>
Run Code Online (Sandbox Code Playgroud)\n\n

<script ...>然后你可以在页面底部编写该部分,例如:

\n\n
{% extends \'base.html\' %}\n{% load static %}\n\n{% block content %}\n  {% for post in object_list %}\n  <div class=\'post-entry\'>\n    <h2><a href="{% url \'post_detail\' post.pk %}">{{ post.title }}</h2>\n      <p>{{ post.body }}</p>\n  </div>\n  {% endfor %}\n{% endblock %}\n\n{% block js %}\n<script type="text/javascript" src="{% static \'js/test.js\' %}"></script>\n{% endblock %}
Run Code Online (Sandbox Code Playgroud)\n\n

您当然可以在{% block ...%} ... %{ endblock %}部件之外定义变量等。但所呈现的一切如果您从基本模板继承,则外部

\n