tornado模板引擎语法

tornado的模板引擎

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

模板语法

1、变量输出
{{ ... }}
能够直接输出render时传过来的变量python

2、表达式输出
输出python表达式,经过AutoEscape设置插入和输出{% %}.web

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

这些标签能够被转移为{{!, {%!, and {#!
若是须要包含文字{{, {%, or {# 在输出中使用app

4、
{% 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.

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

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

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

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

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

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

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

9、for循环
{% for *var* in *expr* %}...{% end %}
这和 python 的for 是同样的。 {% break %}
{% continue %} 语句是能够用于循环体之中的。

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

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

12、import引入包
{% import *module* %}
和python代码同样的声明 import

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

十4、渲染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.

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

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

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

相关文章
相关标签/搜索