一 宏
宏类似常规编程语言中的函数。它们用于把常用行为作为可重用的函数,取代 手动重复的工作。如果宏在不同的模板中定义,你需要首先使用 import,比如
{% macro input(name, value='', type='text', size=20) -%} <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}"> {%- endmacro %}
在命名空间中,宏之后可以像函数一样调用:
<p>{{ input('username') }}</p> <p>{{ input('password', type='password') }}</p>
二 call宏和{{ caller() }}
这里我们使用了”{% call %}”语句块来调用宏,语句块中包括了一段生成”Delete”按钮的代码。运行下试试,你会发现每个用户名后面都出现了”Delete”按钮,也就是”{{ caller( ) }}”部分被调用者”{% call %}”语句块内部的内容替代了。这个跟函数传个参数进去没啥大区别,主要是有些时候HTML语句太复杂(如上例),不方便写在调用参数上,所以就写在”{% call %}”语句块里了
三 宏向调用者传递参数
{% macro list_users(users) -%}
<table>
<tr><th>Name</th><th>Gender</th><th>Action</th></tr>
{%- for user in users %}
<tr><td>{{ user.name |e }}</td>{{ caller(user.gender) }}</tr>
{%- endfor %}
</table>
{%- endmacro %}
{% call(gender) list_users(users) %}
六 包含 (Include)
使用的方法就是”{% include %}”语句。其功能就是将另一个模板加载到当前模板中,并直接渲染在当前位置上。它同导入”import”不一样,”import”之后你还需要调用宏来渲染你的内容,”include”是直接将目标模板渲染出来。它同block块继承也不一样,它一次渲染整个模板文件内容,不分块
当”include”的模板文件不存在时,程序会抛出异常。你可以加上”ignore missing”关键字,这样如果模板不存在,就会忽略这段”{% include %}”语句。
1
|
{% include 'footer.html' ignore missing %}
|
“{% include %}”语句还可以跟一个模板列表:
1
|
{% include ['footer.html','bottom.html','end.html'] ignore missing %}
|