将自定义python函数传递到龙卷风模板

Cyb*_*min 3 python tornado

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

就像def trimString(data): return data[0:20]把它推入我的龙卷风文件一样.这应该允许我修剪字符串.

这可能吗?

谢谢.

Col*_*ean 13

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

IE:

在ui_methods.py中:

def trim_string(data):
    return data[0:20]
Run Code Online (Sandbox Code Playgroud)

在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()
Run Code Online (Sandbox Code Playgroud)

在main.html中:

....
{{ trim_string('a string that is too long............') }}
....
Run Code Online (Sandbox Code Playgroud)

Andy Boot的解决方案也可以使用,但在每个模板中自动访问这样的功能通常很不错.

  • 显然现在你的示例`trim_string`方法将始终接收处理程序作为第一个参数. (2认同)

and*_*oot 5

您还可以将函数作为模板变量传递,如下所示:

 template_vars['mesage'] = 'hello'
 template_vars['function'] = my_function # Note: No ()

        self.render('home.html',
            **template_vars
        )
Run Code Online (Sandbox Code Playgroud)

然后在您的模板中,您将其称为:

 {{ my_function('some string') }}
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以在Tornado中导入函数.我认为这是最干净的解决方案.在模板的顶部,只需执行以下操作:

{% import lib %}
Run Code Online (Sandbox Code Playgroud)

以后你可以做

{{ trim_string(data)}}
Run Code Online (Sandbox Code Playgroud)