官方文档
本文只是官方文档的部分摘录,只记录了常用语法,和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 %}
{% for item in seq %}
- {{ item }}
{% endfor %}
{% endraw %}
Line Statements,需要在在environment中配置line_statement_prefix
# for item in seq:
{{ item }} ## this comment is ignored
# endfor
Inheritance
{% block title %}{% endblock title %} - My Webpage
{% extends "base.html" %}
{% block title %}Index{% endblock title %}
父模板block提供站位符,子模板block提供数据覆盖
super()可以获得父模板中的数据
endblock title可省略title
for
{% for row in rows %}
{{ row }}
{% 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
{% for user in users %}
- {{ user.username|e }}
{% else %}
- no users found
{% endfor %}
for if
{% for user in users if not user.hidden %}
{{ user.username|e }}
{% endfor %}
递归 for
{%- for item in sitemap recursive %}
- {{ item.title }}
{%- if item.children -%}
{%- endif %}
{%- endfor %}
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) -%}
{%- endmacro %}
{{ input('username') }}
{{ input('password', type='password') }}
块和宏参见(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 %}