Tornado templates模板渲染語法總結

Edit

Tornado templates模板渲染語法總結

工作需要研究了一下tornado的模板渲染語法,寫了個測試,總結了一下相關語法,聊作筆記如下。

tornado本身非常靈活,支持幾乎所有python支持的模板語言。除此之外,它本身也提供了一個輕量級的模板,放在tornado.template中。

測試用例

代碼清單1:tornado_template.py

import tornado.httpserver
import tornado.ioloop
import tornado.web

# define one "add" customization funcation which will be used in the assigned template file.
def add(x, y):
    return (x+y)

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        items = ["item1","item2","item3"]
        # render the corresponding template file, and pass the "**args" to the assigned template
        # not only we can pass the realted parameters, but also can pass the related functions.
        # so extendible and powerful! :)
        items2 = ["item1", "item2"]
        def checked(item):
            return 'checked=checked' if item in items2 else ''
        self.render("template_test.html", items=items, add=add, items2=items2, checked=checked)

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8081)
    tornado.ioloop.IOLoop.instance().start()

代碼清單2:template_test.html

<html>
<head>
<title>template function test</title>
</head>
<body>
<ul>
{% for item in items %}
    <li>{{ escape(item) }}</li>
    <li> <input  value={{item}} name={{item}}  type="checkbox" {{checked(item)}} /> {{item}}</li>
{% end %}

{{ add(2,2) }}
</ul>
</body>
</html>

在同一文件夾中創建如上兩個文件,然後在命令行運行python tornado_temp_test.py,再在瀏覽器打開localhost:8081,可以看到如下界面:

Alt text

查看改網頁的源代碼爲:

<html>
<head>
<title>template function test</title>
</head>
<body>
<ul>

<li>item1</li>
<li> <input value=item1 name=item1 type="checkbox" checked=checked /> item1</li>

<li>item2</li>
<li> <input value=item2 name=item2 type="checkbox" checked=checked /> item2</li>

<li>item3</li>
<li> <input value=item3 name=item3 type="checkbox"  /> item3</li>

4
</ul>
</body>
</html>

測試用例解釋

  1. 在程序中,我們通過語句self.render("template_test.html", items=items, add=add, items2=items2, checked=checked)來渲染模板,其中render的第一個參數爲模板文件,後面的所有參數會被傳入模板文件中。此處可以將其他所有參數放入一個參數中,然後用參數解析語法**kwargs來傳入。如此處的調用等價於:
    kwargs = {
    'items': items,
    'items2': items2,
    'add':add,
    'checked':checked
    }
    self.render("template_test.html", **kwargs)
    
  2. 渲染函數將模板中的相關語法進行解析,將動態生成的數據插入其中,生成了新的頁面,展示出來就成了上圖看到的樣子。此處用到的語法包括:
    • {% for item in items %} ... {% end %}:相當於python中的for語句。
    • {{ add(2,2) }}執行了python中的add(2, 2),將結果放在此處,即圖中我們看到的4{{checked(item)}}同理。
    • value={{item}}將循環中產生的item賦給value,查看網頁源代碼可知<input value={{item}} name={{item}} type="checkbox" {{checked(item)}} />被解析成了<input value="item1" name="item1" type="checkbox" checked="checked"/>

模板語法彙總(來自官方文檔

Template expressions are surrounded by double curly braces: {{ ... }}. The contents may be any python expression, which will be escaped according to the current autoescape setting and inserted into the output. Other template directives use {% %}. These tags may be escaped as {{! and {%! if you need to include a literal {{ or {% in the output.

To comment out a section so that it is omitted from the output, surround it with {# ... #}.

{% apply *function* %}...{% end %}

Applies a function to the output of all template code between apply and end:

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

{% autoescape *function* %}

Sets the autoescape mode for the current file. This does not affect other files, even those referenced by {% include %}. Note that autoescaping can also be configured globally, at the Application or Loader.:

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

{% block *name* %}...{% end %}

Indicates a named, replaceable block for use with {% extends %}. Blocks in the parent template will be replaced with the contents of the same-named block in a child template.:

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

<!-- mypage.html -->

{% extends "base.html" %}
{% block title %}My page title{% end %}

{% comment ... %}

A comment which will be removed from the template output. Note that there is no {% end %} tag; the comment goes from the word comment to the closing %} tag.

{% extends *filename* %}

Inherit from another template. Templates that use extends should contain one or more block tags to replace content from the parent template. Anything in the child template not contained in a block tag will be ignored. For an example, see the {% block %} tag.

{% for *var* in *expr* %}...{% end %}

Same as the python for statement.

{% from *x* import *y* %}

Same as the python import statement.

{% if *condition* %}...{% elif *condition* %}...{% else %}...{% end %}

Conditional statement - outputs the first section whose condition is true. (The elif and else sections are optional)

{% import *module* %}

Same as the python import statement.

{% include *filename* %}

Includes another template file. The included file can see all the local variables as if it were copied directly to the point of the include directive (the {% autoescape %} directive is an exception). Alternately, {% module Template(filename, **kwargs) %} may be used to include another template with an isolated namespace.

{% module *expr* %}

Renders a UIModule. The output of the UIModule is not escaped:

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

{% raw *expr* %}

Outputs the result of the given expression without autoescaping.

{% set *x* = *y* %}

Sets a local variable.

{% try %}...{% except %}...{% finally %}...{% else %}...{% end %}

Same as the python try statement.

{% while *condition* %}... {% end %}

Same as the python while statement.

參考鏈接:

【1】:template@tornado 學習記錄
【2】:Introduction to Tornado中文版相關內容
【3】:官方文檔中的相關內容


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章