我在 base.html
文件中使用了 include
和 extends
并希望它们按顺序包含。但是 extends
模板附加到文件的末尾。
我希望我的模板给我输出:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>Test String from block !</p>
<footer>text from footer.</footer>
</body>
</html>
但目前的结果是:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<footer>text from footer.</footer>
</body>
</html>
<p>Test String from block !</p>
在 base.html
中,首先包含 header.html
,然后是 content.html
,然后是 footer.html
但呈现的顺序是 header.html
, footer.html
, content.html
.
index.html
{% extends "base.html" %}
{% block content %}
<p>Test String from block !</p>
{% endblock %}
base.html
{% include "header.html" %}
<body>
{% extends "content.html" %}
{% include "footer.html" %}
header.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
content.html
{% block content %}
{% endblock %}
footer.html
<footer>text from footer.</footer>
</body>
</html>
最佳答案
我建议结构略有不同。我最近使用了这样的结构并得到了正确的结果。
index.html:
{% extends "base.html" %}
{% block head %}
<!-- if you want to change the <head> somehow, you can do that here -->
{% endblock head %}
{% block content %}
<body>
<p>Test String from block !</p>
{% include 'content.html' %}
</body>
{% include 'footer.html' %}
{% endblock content %}
基础.html:
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<meta charset="UTF-8">
<title>Title</title>
{% endblock head %}
</head>
{% block content %}
{% endblock content %}
</html>
内容.html:
<!-- whatever you want in here -->
页脚.html:
<footer>text from footer.</footer>
希望对您有所帮助。
关于python - Jinja2 include & extends 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555769/