tornado模板引擎语法

tornado的模板引擎

tornado的模板语法非常灵活,本文中的模板语法都是经源码文档查阅的,并调试可用。

模板语法

一、变量输出
{{ ... }}
可以直接输出render时传过来的变量

二、表达式输出
输出python表达式,通过AutoEscape设置插入和输出{% %}.

三、注释一个部分,防止他被输出
{# ... #}.

这些标签可以被转移为{{!, {%!, and {#!
如果需要包含文字{{, {%, or {# 在输出中使用

四、
{% apply *function* %}...{% end %}
将函数应用于所有模板之间的输出 apply
end::

    {% apply linkify %}{{name}} said: {{message}}{% end %}

Note that as an implementation detail apply blocks are implemented
as nested functions and thus may interact strangely with variables
通过设置 ``{% set %}``, or the use of ``{% break %}`` or ``{% continue %}``
within loops.

五、
{% autoescape *function* %}
设置当前文件的AutoEscape模式。这不影响
其他文件,甚至那些引用{% include %}. 请注意,
autoescaping也能设置全局生效, 或在 .Application
or Loader.::

    {% autoescape xhtml_escape %}
    {% autoescape None %}

六、模板替换
{% block *name* %}...{% end %}
指定一个可被替换的块 {% extends %}.
父块的块可以被字块所替换,例如::

    <!-- base.html -->
    <title>{% block title %}Default title{% end %}</title>

    <!-- mypage.html -->
    {% extends "base.html" %}
    {% block title %}My page title{% end %}

七、模板
{% comment ... %}
将模板输出中的注释去除. 当遇到 {% end %} 标签时会结束; 在 comment%} 标签之间写参数.

八、模板继承
{% extends *filename* %}
从另一个模板那里继承过来. extends包含一个或多个标签以从父模块那继承过来 ,不包含在块中的子模板及时存在标签页也会被忽略 , 详见 {% block %} 标签,列 如:

九、for循环
{% for *var* in *expr* %}...{% end %}
这和 python 的for 是一样的。 {% break %}
{% continue %} 语句是可以用于循环体之中的。

十、from引入包
{% from *x* import *y* %}
这和python的 import语法是一样的。

十一、if分支
{% if *condition* %}...{% elif *condition* %}...{% else %}...{% end %}
表达式为真时,第一个条件语句会被输出 (在 elifelse之间都是可选的)

十二、import引入包
{% import *module* %}
和python代码一样的声明 import

十三、引入模板文件
{% include *filename* %}
包含另一个模板文件,所包含的模板文件可以使用所有的局部变量,如果是直接被 include进来的话(其中 {% autoescape %} 是个例外).
另外, {% module Template(filename, **kwargs) %} 可以将两个模板的命名空间隔离.

十四、渲染UI模块
{% module *expr* %}
渲染一个 ~tornado.web.UIModule. The output of the UIModule is
not escaped::

    {% module Template("foo.html", arg=42) %}

``UIModules`` are a feature of the `tornado.web.RequestHandler`
class (and specifically its ``render`` method) and will not work
when the template system is used on its own in other contexts.

十五、不转义输出
{% raw *expr* %}
输出的结果表达式没有autoescaping

十六、定义变量
{% set *x* = *y* %}
设置局部变量.
十七、异常处理
{% try %}...{% except %}...{% else %}...{% finally %}...{% end %}
这和python try 陈述相同.
十八、while语句
{% while *condition* %}... {% end %}
和python语句一样 while{% break %}
{% continue %} 可以在while循环中使用。

{% whitespace *mode* %}
设置当前文件的剩余空白模式
(直到遇到下一个 {% whitespace %} 时才会结束). See
filter_whitespace 对于可用选项,来自 Tornado 4.3.
"""

posted on 2017-04-18 15:47  最美代码  阅读(6277)  评论(4编辑  收藏  举报