天天看点

Tornado templates模板渲染语法总结 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

,可以看到如下界面:

Tornado templates模板渲染语法总结 Tornado templates模板渲染语法总结

查看改网页的源代码为:

<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:

{% 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】:[email protected] 学习记录

【2】:Introduction to Tornado中文版相关内容

【3】:官方文档中的相关内容