什么是宏:
- 宏类似常规编程语言中的函数。它们用于把常用行为作为可重用的函数,取代手动重复的工作。
宏的实例:
- 宏渲染表单的实例:
{% 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>
包含(include)
- include 语句用于包含一个模板,并在当前命名空间中返回那个文件的内容渲 染结果
- 被包含的模板默认可以访问活动的上下文中的变量。
{% include 'header.html' %}
Body
{% include 'footer.html' %}
- 可以把一句
include
用ignore missing
标记,这样如果模板不存在Jinja会忽略这条语句。当与with
或without context
语句联合使用时,它必须被放在上下文可见性语句之前 。
{% include "sidebar.html" ignore missing %}
{% include "sidebar.html" ignore missing with context %}
{% include "sidebar.html" ignore missing without context %}
- 你也可以提供一个模板列表,它会在包含前被检查是否存在。第一个存在的模板会 被包含进来。如果给出了
ignore missing
,且所有这些模板都不存在,会退化 至不做任何渲染,否则将会抛出一个异常。
{% include ['page_detailed.html', 'page.html'] %}
{% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}
导入(from xx import oo)
-
Jinja2 支持在宏中放置经常使用的代码。这些宏可以被导入,并不同的模板中使用。这 与 Python 中的 import 语句类似。要知道的是,导入量会被缓存,并且默认下导入的 模板不能访问当前模板中的非全局变量。更多关于导入和包含的上下文行为见 导入上下文行为 。
-
有两种方式来导入模板。你可以把整个模板导入到一个变量或从其中导入请求特定的宏 /导出量。
-
比如我们有一个渲染表单(名为
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 %}
- 最简单灵活的方式是把整个模块导入为一个变量。这样你可以访问属性:
{% import 'forms.html' as forms %}
<dl>
<dt>Username</dt>
<dd>{{ forms.input('username') }}</dd>
<dt>Password</dt>
<dd>{{ forms.input('password', type='password') }}</dd>
</dl>
<p>{{ forms.textarea('comment') }}</p>
- 此外你也可以从模板中导入名称到当前的命名空间:
{% from 'forms.html' import input as input_field, textarea %}
<dl>
<dt>Username</dt>
<dd>{{ input_field('username') }}</dd>
<dt>Password</dt>
<dd>{{ input_field('password', type='password') }}</dd>
</dl>
<p>{{ textarea('comment') }}</p>
导入上下文行为:
为什么使用导入上下文
- 在使用宏的时候和
include
不同,不会导入从视图函数传来的context上下文
,所以在导入宏的时候可以指定导入上下文。
{% from 'forms.html' import input with context %}
{% include 'header.html' without context %}