Jinja2 忽略未找到的对象的 UndefinedErrors

发布于 2024-11-10 13:20:47 字数 243 浏览 5 评论 0原文

引用时我的很多模板都会损坏

 {{ 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

好多鱼好多余 2024-11-17 13:20:47

在 Sean 出色且有用的答案的基础上,我执行了以下操作:

from jinja2 import Undefined
import logging

class SilentUndefined(Undefined):
    '''
    Dont break pageloads because vars arent there!
    '''
    def _fail_with_undefined_error(self, *args, **kwargs):
        logging.exception('JINJA2: something was undefined!')
        return None

然后是我所说的 env = Environment(undefined=SilentUndefine) 。

在我使用的django_jinja库中,上面的内容在base.py中,实际上是对initial_params的修改

Building off of Sean's excellent and helpful answer, I did the following:

from jinja2 import Undefined
import logging

class SilentUndefined(Undefined):
    '''
    Dont break pageloads because vars arent there!
    '''
    def _fail_with_undefined_error(self, *args, **kwargs):
        logging.exception('JINJA2: something was undefined!')
        return None

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 of initial_params

得不到的就毁灭 2024-11-17 13:20:47

我基于@rattray上面的答案构建:

from jinja2 import Undefined, Template

class SilentUndefined(Undefined):
    def _fail_with_undefined_error(self, *args, **kwargs):
        return ''

然后将其与模板字符串一起使用:

person_dict = {'first_name': 'Frank', 'last_name': 'Hervert'}
t2 = Template("{{ person1.last_name }}, {{ person.last_name }}", undefined=SilentUndefined)

print t2.render({'person': person_dict})                                                                         
# ', Hervert'

直接从字符串渲染模板而不是使用环境时,我需要忽略错误。

I built on @rattray's answer above:

from jinja2 import Undefined, Template

class SilentUndefined(Undefined):
    def _fail_with_undefined_error(self, *args, **kwargs):
        return ''

Then used it with template string:

person_dict = {'first_name': 'Frank', 'last_name': 'Hervert'}
t2 = Template("{{ person1.last_name }}, {{ person.last_name }}", undefined=SilentUndefined)

print t2.render({'person': person_dict})                                                                         
# ', Hervert'

I needed to ignore the errors when rendering a Template from string directly instead of using Environment.

鱼忆七猫命九 2024-11-17 13:20:47

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

魄砕の薆 2024-11-17 13:20:47

我还需要重置类的魔术方法以使对象属性等正常工作。添加到@rattray——

from jinja2 import Undefined, Template

class SilentUndefined(Undefined):
    def _fail_with_undefined_error(self, *args, **kwargs):
        return ''

    __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
        __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
        __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
        __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \
        __float__ = __complex__ = __pow__ = __rpow__ = \
        _fail_with_undefined_error        

成为一个神社设置是有意义的。很多人都会使用 django 模板,默认情况下这些模板是静默的。

I also needed to reset the class's magic methods to make object attributes etc work correctly. Adding to @rattray --

from jinja2 import Undefined, Template

class SilentUndefined(Undefined):
    def _fail_with_undefined_error(self, *args, **kwargs):
        return ''

    __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
        __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
        __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
        __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \
        __float__ = __complex__ = __pow__ = __rpow__ = \
        _fail_with_undefined_error        

It'd make sense to be a jinja setting. A lot of people would be coming from django templates which are silent by default.

2024-11-17 13:20:47

也在寻找解决方案并使用@s29 SilentUndefined类,但是当尝试调用未定义变量时,我发现了“'str'对象不可调用”错误,所以这是我的解决方法,它可能对某人有帮助

class SilentUndefined(Undefined):

    def _fail_with_undefined_error(self, *args, **kwargs):
        class EmptyString(str):
            def __call__(self, *args, **kwargs):
                return ''
        return EmptyString()

 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
    __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
    __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
    __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \
    __float__ = __complex__ = __pow__ = __rpow__ = \
    _fail_with_undefined_error

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

class SilentUndefined(Undefined):

    def _fail_with_undefined_error(self, *args, **kwargs):
        class EmptyString(str):
            def __call__(self, *args, **kwargs):
                return ''
        return EmptyString()

 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
    __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
    __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
    __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \
    __float__ = __complex__ = __pow__ = __rpow__ = \
    _fail_with_undefined_error
蓝眼睛不忧郁 2024-11-17 13:20:47

如果您在 ansible 中使用 Jinja2,有一个设置可以让您指定缺失变量的默认行为。在 ansible.cfg 中:

[Defaults]
error_on_undefined_vars=False

请注意,此过滤器和默认过滤器仅在缺少的内容位于点路径末尾时才有效。例如:如果缺少“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:

[Defaults]
error_on_undefined_vars=False

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文