[英]Passing a custom python function into a tornado template
我想編寫一個自定義函數並將其傳遞給我的龍卷風模板。
像def trimString(data): return data[0:20]
然后將其推入我的龍卷風文件。 這應該允許我修剪字符串。
這可能嗎?
謝謝。
在文檔中並不是特別清楚 ,但是您可以通過在模塊中定義此函數並將模塊作為ui_methods
參數傳遞給tornado.web.Application
來tornado.web.Application
此ui_methods
。
IE:
在ui_methods.py中:
def trim_string(data):
return data[0:20]
在app.py中:
import tornado.ioloop
import tornado.web
import ui_methods
class MainHandler(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()
在main.html中:
....
{{ trim_string('a string that is too long............') }}
....
Andy Boot的解決方案也可以使用,但是在每個模板中自動訪問這樣的功能通常很不錯。
您還可以將函數作為模板變量傳遞,如下所示:
template_vars['mesage'] = 'hello'
template_vars['function'] = my_function # Note: No ()
self.render('home.html',
**template_vars
)
然后在您的模板中,您將其稱為:
{{ my_function('some string') }}
您可以在Tornado中導入函數。 我認為這是最干凈的解決方案。 在模板的頂部,只需執行以下操作:
{% import lib %}
以后你可以做
{{ trim_string(data)}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.