继承

道盒发布支持简单的子母模板结构。在母模板中定义block块,可以在子模板继承并修改block块内容。

例如母模板 base.html

<!DOCTYPE html>
<html lang="en">
<head>
    {% block head %}
    <link rel="stylesheet" href="style.css" />
    <title>{% block title %}{% endblock title %} - My Webpage</title>
    {% endblock head %}
</head>
<body>
    <div id="content">{% block content %}{% endblock content %}</div>
    <div id="footer">
        {% block footer %}
        &copy; Copyright 2008 by <a href="https://everkm.cn/">you</a>.
        {% endblock footer %}
    </div>
</body>
</html>

上面定义了4个block(head, title, content, footer)区块,在子模板中继承后,可以根据需要覆盖指定的block区块。

子模板(通过extends继承)child.html

{% extends "base.html" %}

{% block title %}Index{% endblock title %}

{% block head %}
    {{ super() }}
    <style type="text/css">
        .important { color: #336699; }
    </style>
{% endblock head %}

{% block content %}
    <h1>Index</h1>
    <p class="important">
      Welcome to my awesome homepage.
    </p>
{% endblock content %}

子模板中,block块中使用super()表示渲染父模板中的同名block块到此处。下面三层模板嵌套

// grandparent.html
{% block hey %}hello{% endblock hey %}

// parent.html
{% extends "grandparent.html" %}
{% block hey %}hi and grandma says {{ super() }} {% block ending %}sincerely{% endblock ending %}{% endblock hey %}

// child.html
{% extends "parent.html" %}
{% block hey %}dad says {{ super() }}{% endblock hey %}
{% block ending %}{{ super() }} with love{% endblock ending %}

上面模板渲染结果(不含空白)为:“dad says hi and grandma says hello sincerely with love”。

block块不支持外部新赋值的变量,如

错误示范❌, 下面的输出都会报错。

{% set name="everkm" %}
{% set_global site="everkm.cn" %}

{% block header %}
{{name}}
{{site}}
{% endblock %}