包含块的烧瓶模板问题

flask template problem with included blocks

您好,在我的模板中显示块时遇到了一些问题。 我有5个文件。 3 个包含在 base.html 中,一个确实从它扩展。

问题出在页眉和页脚文件中称为元和页脚的块。 它们在我的 index.html.

中是空的

只有在 base.html 文件中直接声明的内容块有效。 navigation.html 工作正常,但没有声明块。

在 base.html 文件模板中包含带块的文件是否有问题,还是我遗漏了什么?

header.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% block meta %}
    {% endblock %}
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="{{ url_for('index') }}">Brand</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="#navbarSupportedContent">
                {% include 'navigation.html' %}
            </div>
        </div>
    </nav>

footer.html

</body>
<footer>
    {% block footer %}
    {% endblock %}
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
</footer>
</html>

base.html

{% include 'header.html' %}
        {% block content %}
        {% endblock %}
{% include 'footer.html' %}

index.html

{% extends 'base.html' %}
{% block meta %}
    <title>Titel for index page</title>
{% endblock %}
{% block title %}Willkommen bei Brand{% endblock %}
{% block content %}
    <p>This block works</p>
{% endblock %}

navigation.html

<ul class="navbar-nav ms-auto">
    <li class="nav-item">
        <a class="nav-link {{ active_home }}" aria-current="page" href="{{ url_for('index') }}">Home</a>
    </li>
    <li class="nav-item">
        <a class="nav-link {{ active_contact }}" aria-current="page" href="{{ url_for('contact') }}">Kontakt</a>
    </li>
    <li class="nav-item">
        <a class="nav-link {{ active_impress }}" aria-current="page" href="{{ url_for('index') }}">Impressum</a>
    </li>
</ul>

Is it a problem to include files with blocks in base.html file template or did i miss something?

块在继承链外不可见。如果用 required 标记块,您将看到错误:

{% block meta required %}
"Required block 'meta' not found"

include 的模板呈现为单独的继承链,因此它不会看到来自 index.html.

的块

The include tag is useful to include a template and return the rendered contents of that file into the current namespace https://jinja.palletsprojects.com/en/latest/templates/#include

你不应该期望你的块被传递给 include 的模板,并相应地设计模板继承。例如,参见 base template in jinja documentation