简体   繁体   中英

Passing a custom python function into a tornado template

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

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

Is this possible?

Thanks.

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.

IE:

in ui_methods.py:

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

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()

in main.html:

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

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

You can also pass the function in as a template variable like this:

 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') }}

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

{% import lib %}

later you can do

{{ trim_string(data)}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM