Search code examples
pythontornado

Custom template pipe fuctions in Tornado


How do you define a custom template pipe function that is available on all template in Tornado.

Trying to achieve something like this:

{{ name | transform_me }}

Solution

  • You can pass custom ui_methods with Application, that will be available in all templates:

    import tornado.ioloop
    import tornado.web
    
    
    class MyHandler(tornado.web.RequestHandler):
        def get(self):
            self.render("mytemplate.html")
    
    
    def my_custom_function(handler, *args):
        # handler is the RequestHandler of current handled request  
        # args are the agrs passed through template
        return 'my_custom {}'.format(str(args)) 
    
    if __name__ == "__main__":
        application = tornado.web.Application(
            [(r"/", MyHandler),],
            # expose function to the templates
            ui_methods={'my_custom_function': my_custom_function}
        )
        application.listen(8888)
        tornado.ioloop.IOLoop.instance().start()
    

    and template file

    {{ my_custom_function('adsadasda', 'qweqweq') }}