python - Jinja2 include & extends 没有按预期工作

标签 python flask jinja2

我在 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.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/

相关文章:

使用 Azure Log Analytics 进行 Python 应用程序日志记录

python - flask 棉花糖属性错误 : List Object has no Attribute 'data'

python - Jinja 渲染 matplotlib 图?

python - Jinja2 内联注释

Python:捕获特定异常

python - Django 查询功能无法正确过滤用户类型

python - 为什么 iloc() 的一种使用给出了 SettingWithCopyWarning,而另一种却没有?

python - 数据标准化

python - 使用 get_template jinja2 生成动态 XML 模板

python-3.x - Flask Dynamo CreateTable 操作问题(botocore.exceptions.ClientError)