import re from jinja2 import evalcontextfilter, Markup, escape
_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
@evalcontextfilter defnl2br(eval_ctx, value): result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n')) for p in _paragraph_re.split(escape(value))) if eval_ctx.autoescape: result = Markup(result) return result
<h1>Members</h1> <ul> @% for user in users %@ <li>@@ user.username|e @@</li> @% endfor %@ </ul>
@% for user in users %@ @%- if loop.index is even %@@% continue %@@% endif %@ ... @% endfor %@
key-value形式的循环:
1 2 3 4 5 6
<dl> @% for key, value in my_dict.iteritems() %@ <dt>@@ key|e @@</dt> <dd>@@ value|e @@</dd> @% endfor %@ </dl>
if判断
1 2 3 4 5 6 7
@% if kenny.sick %@ Kenny is sick. @% elif kenny.dead %@ You killed Kenny! You bastard!!! @% else %@ Kenny looks okay --- so far @% endif %@
赋值语句
1 2
@% set navigation = [('index.html','Index'), ('about.html','About')] %@ @% setkey, value = call_something() %@
块赋值
1 2 3 4
@% set navigation %@ <li><ahref="/">Index</a> <li><ahref="/downloads">Downloads</a> @% endset %@
包含模板
1 2 3 4 5 6
@% include 'header.html' %@ @% include "sidebar.html" ignore missing %@ @% include "sidebar.html" ignore missing with context %@ @% include "sidebar.html" ignore missing without context %@ Body @% include 'footer.html' %@
i18n
国际化例子
1 2
<p>@% trans user=user.username %@Hello @@ user @@!@% endtrans %@</p> @@_('Hello %(user)s!')|format(user=user.username) @@
临时指定autoescape
1 2 3 4 5 6 7
@% autoescape true %@ Autoescaping is active within this block @% endautoescape %@
@% autoescape false %@ Autoescaping is inactive within this block @% endautoescape %@