web.py自带Templetor模板:
一个完整的web.py:
code.py:
#!/usr/bin/env python
# coding:utf-8
import web, sys
reload(sys)
sys.setdefaultencoding('utf-8')
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
render = web.template.render('templates')
class hello:
def GET(self, name):
return render.hello('a', 'b', 'c', [1,2,3])
if __name__ == "__main__":
app.run()
hello.html:
$def with(a,b,c,list)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1>web.py首页</h1>
$if b > 1:
$b
$else:
<h1>meiyou</h1>
<br>
$if list:
$for i in list:
$i
</body>
</html>
页面显示:

注:Templetor严格遵守缩进,缩进错误会报错!
渲染方式:
render = web.template.render('templates')
return render.hello('a', 'b', 'c', [1,2,3])
Web.py框架结合Cheetah模板
code.py:
#!/usr/bin/env python
# coding:utf-8
from Cheetah.Template import Template
import web, sys
reload(sys)
sys.setdefaultencoding('utf-8')
urls = (
'/(.*)', 'hello'
)
app = web.application(urls, globals())
class hello:
def GET(self, name):
nameSpace = {'title': 'Hello World Example', 'contents': 'Hello World!', "list": [1, 2, 3, 4], "num": 3}
# file-->页面路由 searchList-->发送的的数据(list中dict)
return Template(file='templates/test.html', searchList=[nameSpace])
if __name__ == "__main__":
app.run()
test.html
<body>
#if $num > 1
<p>$num</p>
#end if
$title
#if $contents
<h1 style="color: red">$contents</h1>
#end if
## 单行注释
#*
多行注释
*#
#if $list
#for $i in $list
<li class="cont">$i</li>
#end for
#else
#end if
</body>
页面显示:

扩展:模板继承怎么搞定?
被继承者:base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>$title</title>
</head>
<body>
<h1style="color: green" >我是base,被继承者</h1>
$body
</body>
</html>
注:base.html为被继承的模板,$title及$body是被继承后可自我定义更改的部分。
继承者:test.html
#include "templates/base.html"
#def title
title
#end def
#def body
<h2 style="color: red">我是继承者的body部分!</h2>
#end def
注:test.html为继承者,使用#def title …#end def 和 #def body … #end def 来展示本页需更新的内容。
页面显示:

网友评论