显示所有jinja对象属性

编程入门 行业动态 更新时间:2024-10-13 12:23:56
本文介绍了显示所有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())

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

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

更多推荐

显示所有jinja对象属性

本文发布于:2023-11-28 18:26:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643474.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   对象   jinja

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!