显示所有jinja对象属性 [英] Display all jinja object attributes

查看:46
本文介绍了显示所有jinja对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以在Jinja模板中显示给定对象的所有属性的名称/内容/功能.这将使调试效果不理想的模板更加容易.

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 expected.

我正在使用hyde框架构建一个网站,由于我仍然在学习jinja和hyde的复杂性,因此这将非常方便.

I am building a website using the hyde framework and this would come in quite handy since I am still learning the intricacies of both jinja and hyde.

最初,我曾认为使用attr过滤器会起作用,但这似乎需要一个名称值.我希望不必指定名称即可获取对象的所有可用属性.

Originally, I had thought it would work to use the attr filter, but this seems to require a name value. I would like to to not have to specify the name in order to get all available attributes for the object.

一些google搜索显示django语法如下所示,但是我对django并不熟悉,因此这可能仅适用于数据库项.长话短说,对于任何名为obj

Some google searching showed django syntax looks like the following, but I am not familiar with django so this may only apply to database items. Long story short, I would like a method that works kind of like this for any object named obj

{% for field, value in obj.get_fields %}
    {{ field }} : {{ value }} </br>
{% endfor %}


最终解决方案:

@jayven是正确的,我可以创建自己的jinja2过滤器.不幸的是,使用稳定版本的hyde(0.8.4),这并不是在pythonpath中具有过滤器并在site.yaml文件中设置简单yaml值的简单行为(对此有一个pull-request请求).话虽如此,我能够弄清楚!因此,以下是我的最终解决方案,最终对调试所有未知属性很有帮助.


final solution:

@jayven was right, I could create my own jinja2 filter. Unfortunately, using the stable version of hyde (0.8.4), this is not a trivial act of having a filter in the pythonpath and setting a simple yaml value in the site.yaml file (There is a pull-request for that). That being said, I was able to figure it out! So the following is my final solution which ends up being very helpful for debugging any unkown attributes.

只需使用以下目录树创建本地python包,就可以轻松创建站点特定的hyde扩展

It's easy enough to create site-specific hyde extensions just create a local python package with the following directory tree

hyde_ext
    __init__.py
    custom_filters.py

现在创建扩展名:

from hyde.plugin import Plugin
from jinja2 import environmentfilter, Environment


debug_attr_fmt = '''name:  %s
type:  %r
value: %r'''

@environmentfilter
def debug_attr(env, value, verbose=False):
    '''
    A jinja2 filter that creates a <pre> block
    that lists all the attributes of a given object
    inlcuding the value of those attributes and type.

    This filter takes an optional variable "verbose",
    which prints underscore attributes if set to True.
    Verbose printing is off by default.
    '''

    begin = "<pre class='debug'>\n"
    end = "\n</pre>"

    result = ["{% filter escape %}"]
    for attr_name in dir(value):
        if not verbose and attr_name[0] == "_":
            continue
        a = getattr(value, attr_name)
        result.append(debug_attr_fmt % (attr_name, type(a), a))
    result.append("{% endfilter %} ")
    tmpl = Environment().from_string("\n\n".join(result))

    return begin + tmpl.render() + end

    #return "\n\n".join(result)

# list of custom-filters for jinja2
filters = {
        'debug_attr' : debug_attr
        }

class CustomFilterPlugin(Plugin):
    '''
    The curstom-filter plugin allows any
    filters added to the "filters" dictionary
    to be added to hyde
    '''
    def __init__(self, site):
        super(CustomFilterPlugin, self).__init__(site)

    def template_loaded(self,template):
        super(CustomFilterPlugin, self).template_loaded(template)
        self.template.env.filters.update(filters)

要让Hyde知道扩展名,请将hyde_ext.custom_filters.CustomFilterPlugin添加到site.yaml文件的插件"列表中.

To let hyde know about the extension add hyde_ext.custom_filters.CustomFilterPlugin to the "plugins" list of the site.yaml file.

最后,在文件上进行测试,您可以将其添加到随机页面{{resource|debug_attr}}或以下内容中,甚至获得下划线属性{{resource|debug_attr(verbose=True)}}

Lastly, test it out on a file, you can add this to some random page {{resource|debug_attr}} or the following to get even the underscore-attributes {{resource|debug_attr(verbose=True)}}

当然,我要补充一点,每当发布hyde 1.0时,这似乎在将来会变得容易得多.特别是因为已经有一个拉取请求正在等待实现更简单的解决方案.这是学习更多关于如何使用jinja和hyde的好方法!

Of course, I should add, that it seems like this might become much easier in the future whenever hyde 1.0 is released. Especially since there is already a pull request waiting to implement a simpler solution. This was a great way to learn a little more about how to use jinja and hyde though!

推荐答案

我认为您可以自己实现过滤器,例如:

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

有关详细信息,另请参见文档: http://jinja.pocoo.org/docs/api/#custom-filters

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

这篇关于显示所有jinja对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆