官方文档
本文只是官方文档的部分摘录,只记录了常用语法,和python非常类似,方便快速理解使用
语法
{% ... %} for Statements
{{ ... }} for Expressions to print to the template output
{# ... #} for Comments not included in the template output
# ... ## for Line Statements
获得属性
{{ foo.bar }}
{{ foo['bar'] }}
去掉空白字符
{% for item in seq -%}
{{ item }}
{%- endfor %}
escaping,手动逃逸,自动逃逸会有性能问题
{{ user.username|e }}
输出大括号,裸语句块
{{‘{}’}}
{% raw %}
<ul>
{% for item in seq %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endraw %}
Line Statements,需要在在environment中配置line_statement_prefix
# for item in seq:
<li>{{ item }}</li> ## this comment is ignored
# endfor
Inheritance
<title>{% block title %}{% endblock title %} - My Webpage</title>
{% extends "base.html" %}
{% block title %}Index{% endblock title %}
父模板block提供站位符,子模板block提供数据覆盖
super()可以获得父模板中的数据
endblock title可省略title
for
{% for row in rows %}
<li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
{% endfor %}
loop.index
loop.index0
loop.reindex
loop.reindex0
loop.first
loop.last
loop.length
loop.cycle
loop.depth
loop.depth0
loop.previtem
loop.nextitem
else,iteration为空,执行else
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% else %}
<li><em>no users found</em></li>
{% endfor %}
</ul>
for if
{% for user in users if not user.hidden %}
<li>{{ user.username|e }}</li>
{% endfor %}
递归 for
<ul class="sitemap">
{%- for item in sitemap recursive %}
<li><a href="{{ item.href|e }}">{{ item.title }}</a>
{%- if item.children -%}
<ul class="submenu">{{ loop(item.children) }}</ul>
{%- endif %}</li>
{%- endfor %}
</ul>
Loop Controls
{% for user in users %}
{%- if loop.index is even %}{% continue %}{% endif %}
...
{% endfor %}
{% for user in users %}
{%- if loop.index >= 10 %}{% break %}{% endif %}
{%- endfor %}
if Expression,三元表达式
{% extends layout_template if layout_template is defined else 'master.html' %}
模板中的函数macro
{% 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>
块和宏参见(http://www.ttlsa.com/python/flask-jinja2-template-engine-block-and-macro/)
import,导入namespace
{% import 'forms.html' as forms %}
{% from 'forms.html' import input as input_field, textarea %}
Filter,块级别使用Filter
{% filter upper %}
This text becomes uppercase
{% endfilter %}
Assignments,赋值
{% set key, value = call_something() %}
Include 直接导入模板
{% include "sidebar.html" ignore missing %}
Builtin Filters
List of Builtin Tests
List of Global Functions
参见(http://jinja.pocoo.org/docs/2.10/templates/#list-of-builtin-filters)
With Statement 上下文
{% with %}
{% set foo = 42 %}
{{ foo }} foo is 42 here
{% endwith %}
foo is not visible here any longer
i18n,国际化
{% trans book_title=book.title, author=author.name %}
This is {{ book_title }} by {{ author }}
{% endtrans %}