将自定义 python 函数传递给龙卷风模板 [英] Passing a custom python function into a tornado template

查看:26
本文介绍了将自定义 python 函数传递给龙卷风模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个自定义函数并将其传递给我的 tornado 模板.

I want to write a custom function and pass it unto my tornado template fine.

def trimString(data): return data[0:20] 然后把它推送到我的龙卷风文件中.这应该允许我修剪字符串.

Like def trimString(data): return data[0:20] then push this into my tornado file. This should allow me trim strings.

这可能吗?

谢谢.

推荐答案

这不是 在文档中特别清楚,但是您可以通过在模块中定义此函数并将模块传递给 tornado.web.Application 作为ui_methods 参数.

It's not especially clear in the documentation, but you can do this easily by defining this function in a module and passing the module to tornado.web.Application as the ui_methods argument.

我.乙:

在 ui_methods.py 中:

in ui_methods.py:

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

在 app.py 中:

in 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 中:

in main.html:

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

Andy Boot 的解决方案也有效,但在每个模板中都可以自动访问这样的功能通常很好.

Andy Boot's solution also works, but it's often nice to have functions like this automatically accessible in every template.

这篇关于将自定义 python 函数传递给龙卷风模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆