继承
- 作用
可以把一些公用的代码放在模板中,避免每个html写相同的代码
- 语法
模板定义一些接口,让每个html实现自己的特定功能
{% block block_name %}
模板内容
{% endblock %}
{% extends "base.html" %}
{% block block_name %}
{{ super() }} <!--继承模板内容-->
{{ self.bolck_name() }} <!--引用当前页面其他block内容-->
子页面内容 <!--子页面内容-->
{% endblock %}
> 模板内容 子页面内容
include
- 作用
把一个模板引入到另外一个模板中,类似于把一个模板的代码copy到另外一个模板的指定位置
- 语法
{% include 'header.html' %}
宏
- 作用
模板中的宏跟python中的函数类似,可以传递参数,但是不能有返回值,可以将一些经常用到的代码片段放到宏中,然后把一些不固定的值抽取出来当成一个变量
- 语法
{% macro input(name, value='', type='text') %}
<input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{% endmacro %}
<p>{{ input('username') }}</p>
<p>{{ input('password', type='password') }}</p>
- 跨html文件引用
<!-- 方式一 -->
{% import 'macro.html' as macro %}
<!-- 与上下文一起(with context)导入宏 -->
{% import 'macro.html' as macro with context %}
<!-- 方式二 -->
{% from "macro.html" import input %}
Code
# demo.html
{% extends 'base.html' %}
{% block title %}
子模板title
{% endblock %}
{% block head %}
<style></style>
<link rel="stylesheet" href="#">
<script></script>
{% endblock %}
{% block body %}
<!-- 基层父模板block内容 -->
{{ super() }}
<!-- 调用当前页面其他block -->
{{ self.title() }}
<!-- 子模板block特定内容 -->
<h1>子模板body</h1>
<!-- include -->
{% include '_demo.html' %}
<!-- 宏 -->
{% import '_forms.html' as macro %}
<tr>
<td>用户名:</td>
<td>{{ macro.input('username') }}</td>
</tr>
<tr>
<td>备注:</td>
<td>{{ macro.textarea('comments', rows=3) }}</td>
</tr>
{% endblock %}
# base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}父模板title{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='/css/base.css') }}">
<script src="{{ url_for('static', filename='/js/base.js') }}"></script>
{% block head %}待拓展head{% endblock %}
</head>
<body>
{% block body %}
父模板内容
{% endblock %}
</body>
</html>
# _demo.html
<h1>include内容</h1>
<p>name : 张三</p>
<p>age : 18</p>
<p>comment : 这是include的内容</p>
# _forms.html
{% macro input(name, value='', type='text') %}
<input type="{{ type }}" value="{{ value| e }}" name="{{ name }}">
{% endmacro %}
{% macro textarea(name, value='', rows=10, cols=40) %}
<textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols
}}">{{ value|e }}</textarea>
{% endmacro %}