Jinja2的include和extends无法按预期工作

6

我在base.html文件中使用了includeextends,期望它们按顺序被包含。但是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.htmlfooter.html,但呈现的顺序是header.htmlfooter.htmlcontent.htmlindex.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>
2个回答

5
我建议稍微调整一下结构。我最近使用了这样的结构,得到了正确的结果。
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 %}

base.html:

<!DOCTYPE html>
    <html lang="en">
    <head>
        {% block head %}
        <meta charset="UTF-8">
        <title>Title</title>
        {% endblock head %}
    </head>
    {% block content %}
    {% endblock content %}
</html>

content.html:

<!-- whatever you want in here -->

footer.html:

<footer>text from footer.</footer>

希望这有所帮助。

为什么之前会发生那件事?是 Flask/Jinja 的一个 bug 还是我的问题? - M SH
我认为这可能与文件之间相互引用的顺序有关,但我不能确定。 - coralvanda
你的回答非常好,我也会在jinja的Github存储库上提出问题。感谢您的帮助。 - M SH

0

我认为你想要使用include而不是extends

{% extends "content.html" %}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接