Jinja2 忽略未找到的对象的 UndefinedErrors
引用时我的很多模板都会损坏
{{ entity.property }}
我从 Django 切换到 Jinja,但如果未定义实体, 。在某些情况下是否可以忽略未定义的错误,否则我将不得不添加很多
{% if entity %}{{ entity.property }}{% endif %}
包装器。
谢谢, 理查德
I switched to Jinja from Django but a lot of my templates broke when referencing
{{ entity.property }}
if entity is not defined. Is there away to ignore the UndefinedErrors in certain situations, Otherwise I'll have to add in a lot of
{% if entity %}{{ entity.property }}{% endif %}
wrappers.
Thanks,
Richard
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 Sean 出色且有用的答案的基础上,我执行了以下操作:
然后是我所说的 env = Environment(undefined=SilentUndefine) 。
在我使用的django_jinja库中,上面的内容在
base.py
中,实际上是对initial_params
的修改Building off of Sean's excellent and helpful answer, I did the following:
and then
env = Environment(undefined=SilentUndefined)
where I was calling that.In the django_jinja library, which I use, the above is in
base.py
and is actually a modification ofinitial_params
我基于@rattray上面的答案构建:
然后将其与模板字符串一起使用:
直接从字符串渲染模板而不是使用环境时,我需要忽略错误。
I built on @rattray's answer above:
Then used it with template string:
I needed to ignore the errors when rendering a Template from string directly instead of using Environment.
Jinja2 实际上对未定义的实体使用了一个特殊的类。您可以将此
Undefined
类从 Jinja2 子类化为包括__getattr__
和其他属性访问器你想要的甚至能够在未定义的实体上使用并让它们返回一个空白的 unicode 字符串(例如)。Jinja2 actually uses a special class for undefined entities. You can subclass this
Undefined
class from Jinja2 to include__getattr__
and other attribute accessors that you want to be able to use even on undefined entities and have them return a blank unicode string (for example).我还需要重置类的魔术方法以使对象属性等正常工作。添加到@rattray——
成为一个神社设置是有意义的。很多人都会使用 django 模板,默认情况下这些模板是静默的。
I also needed to reset the class's magic methods to make object attributes etc work correctly. Adding to @rattray --
It'd make sense to be a jinja setting. A lot of people would be coming from django templates which are silent by default.
也在寻找解决方案并使用@s29 SilentUndefined类,但是当尝试调用未定义变量时,我发现了“'str'对象不可调用”错误,所以这是我的解决方法,它可能对某人有帮助
Also was looking for a solution and used @s29 SilentUndefined class, but I`ve caught "'str' object is not callable" error when undefined variable was tried to be called, so this is my workaround, it could be helpful for someone
如果您在 ansible 中使用 Jinja2,有一个设置可以让您指定缺失变量的默认行为。在 ansible.cfg 中:
请注意,此过滤器和默认过滤器仅在缺少的内容位于点路径末尾时才有效。例如:如果缺少“c”,
{{ abc }}
将起作用,但如果缺少“b”,仍然会失败并出现 KeyError。If you're using Jinja2 within ansible, there's a setting that lets you specify the default behaviour for a missing variable. In ansible.cfg:
Note that this, and the defaults filter, only works if what's missing is at the end of a dot path. Eg:
{{ a.b.c }}
will work if 'c' is missing, but will still fail with a KeyError if 'b' is missing.