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. """

相關文章
相關標籤/搜索