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 %}
表達式為真時,第一個條件語句會被輸出 (在 elif
和 else
之間都是可選的)
十二、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.
"""