加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 13:03:13 所属栏目:Python 来源:网络整理
导读:我想编写一个自定义函数并将其传递给我的龙卷风模板. 像def trimString(data):返回数据[0:20]然后将其推入我的龙卷风文件. 这应该允许我修剪字符串. 这可能吗? 谢谢. 解决方法 它不是 especially clear in the documentation,但您可以通过在模块中定义此函
我想编写一个自定义函数并将其传递给我的龙卷风模板.

像def trimString(data):返回数据[0:20]然后将其推入我的龙卷风文件.
这应该允许我修剪字符串.

这可能吗?

谢谢.

解决方法

它不是 especially clear in the documentation,但您可以通过在模块中定义此函数并将模块作为ui_methods参数传递给tornado.web.Application来轻松完成此操作.

I.:

在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的解决方案也可以使用,但是在每个模板中自动访问这样的功能通常很不错.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读