好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python学习第二十九课(tornado的模板引擎)

一、render tornado通过render和renderString两个函数来渲染模板。 二、模板语法 1、模板文件 文件扩展名一般以html,也可以用其他的扩展名,只要文件内部符合语法规则。下面的内容假设为index.html文件中。 语法标签有: {# #}{{!, {%!, {#!{{, {%, or {# 2、变量

 <div> {{name}} </div> 
 name = "你是谁?"
self.render('index.html',name) 

3、函数

 {% apply *function* %}

{% end %} 

4、模板替换

 <!-- base.html -->
<title>{% block title %}Default title{% end %}</title>
<!-- mypage.html -->
{% extends "base.html" %}
{% block title %}My page title{% end 
<!-- 这里block,替换base.html中的block块。 

5、模板继承

 {% extends *filename* %} 

6、for循环/while语句

 {% for name in name_list %}
  <div> {{name}} </div>
{% end %}
{% while True %}
  {% if name is "谁" %}
      {% continue %}
  {% print(name) %}
{% end %} 

7、插入模板文件

 {% include *filename* %} 

8、渲染UI模块

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

9、定义变量

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

10、异常处理

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

三、举例

 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("index.html", items=items, add=add, items2=items2, checked=checked) 
 <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的模板引擎)的详细内容...

  阅读:51次