对宏(macro)的理解:
{% macro input(name,value='',type='text') %}
{% endmacro %}
{{ input('name' value='zs')}}
{% macro function(type='text', name='', value='') %}
{% endmacro %}
{% import 'macro.html' as func %}
{% func.function() %}
<form>
<label>用户名:label><input type="text" name="username"><br/>
<label>身份证号:label><input type="text" name="idcard"><br/>
<label>密码:label><input type="password" name="password"><br/>
<label>确认密码:label><input type="password" name="password2"><br/>
<input type="submit" value="注册">
form>
{#定义宏,相当于定义一个函数,在使用的时候直接调用该宏,传入不同的参数就可以了#}
{% macro input(label="", type="text", name="", value="") %}
<label>{{ label }}label><input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{% endmacro %}
<form>
{{ input("用户名:", name="username") }}<br/>
{{ input("身份证号:", name="idcard") }}<br/>
{{ input("密码:", type="password", name="password") }}<br/>
{{ input("确认密码:", type="password", name="password2") }}<br/>
{{ input(type="submit", value="注册") }}
form>
模板继承是为了重用模板中的公共内容。一般Web开发中,继承主要使用在网站的顶部菜单、底部。这些内容可以定义在父模板中,子模板直接继承,而不需要重复书写。
{% block top %} {% endblock %}
{% block top %}
顶部菜单
{% endblock top %}
{% block content %}
{% endblock content %}
{% block bottom %}
底部
{% endblock bottom %}
{% extends 'base.html' %}
{% block content %}
需要填充的内容
{% endblock content %}
Jinja2模板中,除了宏和继承,还支持一种代码重用的功能,叫包含(Include)。它的功能是将另一个模板整个加载到当前模板中,并直接渲染。
{% include 'hello.html' %}
包含在使用时,如果包含的模板文件不存在时,程序会抛出TemplateNotFound异常,可以加上 ignore missing
关键字。如果包含的模板文件不存在,会忽略这条include语句。
{% include 'hello.html' ignore missing %}