简体   繁体   English

龙卷风中的自定义模板管道功能

[英]Custom template pipe fuctions in Tornado

How do you define a custom template pipe function that is available on all template in Tornado. 如何定义一个自定义模板管道功能,该功能可在Tornado中的所有模板上使用。

Trying to achieve something like this: 试图实现这样的目标:

{{ name | transform_me }}

You can pass custom ui_methods with Application, that will be available in all templates: 您可以将自定义ui_methods与Application一起传递,这将在所有模板中可用:

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

You can have your controllers share a Base RequestHandler whose get_template_namespace method is overwritten. 您可以让您的控制器共享一个基本RequestHandler,其get_template_namespace方法将被覆盖。

You probably want to have a filters module. 您可能想要一个过滤器模块。

filters.py filters.py

def transform_me(value):
    # transform value
    return transformed_value


filters = {
   'transform_me': transform_me
}

Shared base class 共享基类

You can add your filters to the template namespace. 您可以将过滤器添加到模板名称空间。 When render is called from handlers that inherit from BaseRequestHandler , your filters will be available. render是从继承处理程序称为BaseRequestHandler ,您的过滤器将可用。

from filters import filters

class BaseRequestHandler(RequestHandler):
   def get_template_namespace(self):
       namespace = super(BaseRequestHandler, self).get_template_namespace()
       namespace.update(filters)
       return namespace

Reference: 参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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