Display all jinja object attributes

前端 未结 1 2081
鱼传尺愫
鱼传尺愫 2021-02-12 20:56

Is there a way to display the name/content/functions of all attributes of a given object in a jinja template. This would make it easier to debug a template that is not acting as

相关标签:
1条回答
  • 2021-02-12 21:22

    I think you can implement a filter yourself, for example:

    from jinja2 import *
    
    def show_all_attrs(value):
        res = []
        for k in dir(value):
            res.append('%r %r\n' % (k, getattr(value, k)))
        return '\n'.join(res)
    
    env = Environment()
    env.filters['show_all_attrs'] = show_all_attrs
    
    # using the filter
    tmpl = env.from_string('''{{v|show_all_attrs}}''')
    class Myobj(object):
        a = 1
        b = 2
    
    print tmpl.render(v=Myobj())
    

    Also see the doc for details: http://jinja.pocoo.org/docs/api/#custom-filters

    0 讨论(0)
提交回复
热议问题