新内容准备再个人blog发布,主要语言为golang 欢迎大家来看 luanruisong.com
项目中用到了python语言的tornado框架与mako模板 由于本人对于python也是第一次接触所以学习任务很重,身在我天朝上国所查到的资料确实叫人无可奈何,而且本人英文水平有限
google这等网站查到的资料千辛万苦才搞定,下面与大家分享一下
首先 tornado大家都知道是python的一个web框架,好处多多 在这里就不一一赘述了,直接上戏肉
tornado是有自己的模板功能的 想使用mako的模板 就须要重写handler的render方法
上代码:
import tornado.web
import tornado.ioloop
import tornado.auth
import tornado.escape
import tornado.options
from tornado.options import define, options
import mako.lookup
import mako.template
import os
class BaseHandler(tornado.web.RequestHandler):
lookup =mako.lookup.TemplateLookup(["./templates"])#这里是模板的路径 这么设置它会在templates文件夹下查找模板
def render_string(self, filename, **kwargs):
'''
Override render_string to use mako template.
Like tornado render_string method, this method
also pass request handler environment to template engin.
'''
#try:
template = self.lookup.get_template(filename)
env_kwargs = dict(
handler = self,
request = self.request,
current_user = self.current_user,
locale = self.locale,
_ = self.locale.translate,
static_url = self.static_url,
xsrf_form_html = self.xsrf_form_html,
reverse_url = self.application.reverse_url,
)
env_kwargs.update(kwargs)
return template.render(**env_kwargs)
#except:
# exception handler
#print "there has excription in render"
def render(self, filename, **kwargs):
self.finish(self.render_string(filename, **kwargs))
这样就重写了handler的render方法,接下来咱们自己写的handler只需要继承这个BaseHandler就可以调用mako模板了
class MakoHandler(BaseHandler):
def get(self):
items = []#传递的参数变量
self.render("tpl.html", title="leaning log", messages=items)
application = tornado.web.Application([(r"/",MakoHandler),])
if __name__ == "__main__":
port="8080"
print "port :",port
print "url:http://localhost:"+port+"/MainHandler for search leaning log"
application.listen(port)
tornado.ioloop.IOLoop.instance().start()
模板页的写法:
1、变量
mako中使用“${}”来定义变量格式。
2、转义符
在定义变量时,如果其中包含特殊符号时记得要使用转义符转换。u负责转换URL地址,h转换HTML,x对XML进行转义,trim就是去空格啦。
3、控制结构
mako模板中使用%来定义控制结构,像if、for、try之类的,关键的就是要使用“%end<name>”来关闭控制结构。这个应该很好理解了
4、注释
这个没什么好说的,两个井号##是当行注释,而<%doc>和</%doc>中间可以写多行注释
5、换行过滤
同python代码中一样,可以使用“\”来强制不换行。
6、Python代码块
在mako模板中可以直接写py代码,这是个功能很强大的地方,python代码写在<%和%>之间即可。
7、模块级代码
上面有说可以直接在mako中上一般的python代码,还有更强大的地方,可以在引入模块和定义函数等等,在<%! %>中定义即可。
这个模块级别的代码块是在引入mako模板时直接加载到内存中的,是优先于render定义的。所以并不能直接用来进行页面内容的输出。我个人感觉就是如果使用<%! %>来引入了模块和函数,就相当于在后台code中引入,可以作为发布后修改code的补丁形式。
8、标签
mako模板中其他的一些功能都是通过标签来定义的,定义格式为<%tagname></%tagname>。前面的多行注释<%doc></%doc>就是标签里的一种。
官方文档对每个标签都有详细的描述,特别是像<%def>、<%namespace>、<%inherit>等都有专门的篇章进行介绍的。
<%page> 定义模板的页面信息
<%include> 引入其他文件
<%def> 定义Python函数
<%namespace> 名称空间,有点.NET的感觉
<%inherit> 继承父模板
<%namespacename:defname> 调用其他名称空间中的函数
<%call> 一样的调用函数
<%doc> 前面有了,就是注释
<%text> Doc,类似于Python的三引号。使用filter定义转义(h/u/t)