首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

tornado template调用后台老板 自定义python 函数

2013-10-27 
tornado template调用后台 自定义python 函数三种方法1。defining this function in a module and passing

tornado template调用后台 自定义python 函数

三种方法

1。defining this function in a module and passing the module to tornado.web.Application as the ui_methods argument.

in ui_methods.py:

?

def trim_string(data):? ? return data[0:20]

?

in app.py:

import tornado.ioloopimport tornado.webimport ui_methodsclassMainHandler(tornado.web.RequestHandler):def get(self):        self.render("main.html")urls =[(r"/",MainHandler)]application = tornado.web.Application(urls, ui_methods=ui_methods)if __name__ =="__main__":    application.listen(8888)    tornado.ioloop.IOLoop.instance().start()

??

in main.html:

....{{ trim_string('a string that is too long............')}}....

?

?

2。pass the function in as a template variable

 template_vars['mesage']='hello' template_vars['function']= my_function # Note: No ()        self.render('home.html',**template_vars        )

?

?

Then in your template you call it like this:

?

{% my_function('some string')%}

?

3。import functions in Tornado. I think this is the cleanest solution. At the top of your template simply do the following:

{%import lib %}

?

{{ trim_string(data)}}

?

热点排行