jinja2:如何让它像djangotemplate一样默默地失败

发布于 2024-11-10 10:26:16 字数 484 浏览 6 评论 0原文

好吧,我没有找到答案,我确信它非常简单,但我只是不知道如何让它像 Django 一样工作,当它找不到

我尝试使用 Undefined 并创建我自己的 undefined 的 变量时但它给了我属性错误等问题。

def silently(*args, **kwargs):
    return u''

class UndefinedSilently(Undefined):
    __unicode__ = silently
    __str__ = silently
    __call__ = silently
    __getattr__ = silently

但是当我在这里尝试这个时,它失败了 TypeError: 'unicode' object is not callable:

{%for dir_name, links in menu_links.items()%}

Well i don't find the answer I'm sure that it's very simple, but i just don't find out how to make it work like Django when it doesn't find a variable

i tried to use Undefined and create my own undefined but it give me problems of attribute error etc.

def silently(*args, **kwargs):
    return u''

class UndefinedSilently(Undefined):
    __unicode__ = silently
    __str__ = silently
    __call__ = silently
    __getattr__ = silently

but when i try this here it fails TypeError: 'unicode' object is not callable:

{%for dir_name, links in menu_links.items()%}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

相对绾红妆 2024-11-17 10:26:17

您正试图任意深入未定义的数据。 menu_links 未定义,因此 Jinja2 创建 UndefinedSilently 类的新实例。然后,它调用该对象的 __getattr__ 方法来获取 items 属性。这将返回一个空白的 unicode 字符串。然后 Python 尝试调用(menu_links.items()())。这会引发 unicode 对象不可调用的错误。

也就是说:

menu_links.items() # becomes
UndefinedSilently().items() # becomes
UndefinedSilently().u''() # from UndefinedSilently.__getattr__

如果您希望能够比一个级别更深,您可以创建一个类,该类对于除 __str____unicode__ 之外的每次访问尝试都返回自身。

def silently(*args, **kwargs):
    return u''

return_new = lambda *args, **kwargs: UndefinedSilently()

class UndefinedSilently(Undefined):
    __unicode__ = silently
    __str__ = silently
    __call__ = return_new
    __getattr__ = return_new

You are trying to go arbitrarily deep into your undefined data. menu_links is undefined, so Jinja2 creates a new instance of your UndefinedSilently class. It then calls the __getattr__ method of this object to get the items attribute. This returns a blank unicode string. Which Python then tries to call (the () of menu_links.items()). Which raises the error that unicode objects are not callables.

That is:

menu_links.items() # becomes
UndefinedSilently().items() # becomes
UndefinedSilently().u''() # from UndefinedSilently.__getattr__

If you want to be able to go deeper than one level you can create a class that returns itself for every access attempt except __str__ and __unicode__.

def silently(*args, **kwargs):
    return u''

return_new = lambda *args, **kwargs: UndefinedSilently()

class UndefinedSilently(Undefined):
    __unicode__ = silently
    __str__ = silently
    __call__ = return_new
    __getattr__ = return_new
古镇旧梦 2024-11-17 10:26:17

这是一个老问题,但它解决了一个相关问题。我重温/回答这个问题是为了帮助其他人参考Django 3.1/3.2/4.0

  1. 转到您的settings.py

  2. 在“选项”中添加以下内容:

    '未定义': jinja2.Undefined
    
  3. 这样,未定义的变量在渲染时将不会出现,即“沉默”。完整的代码应如下所示:

    <代码>{
        '后端': 'django.template.backends.jinja2.Jinja2',
        '目录':[
            BASE_DIR / '模板-jinja2'
        ],
        “APP_DIRS”:正确,
        '选项': {
            '环境': 'config.jinja2.environment',
            '上下文处理器':[],
            '未定义': jinja2.DebugUndefined
    
        },
    },
    
  4. 或者,您可以使用 DebugUndefined 查看未定义的变量,或使用 'StrictUndefine' 在使用未定义变量的情况下引发异常。

This is an old question, but it addresses a relevant issue. I revive/answer this to assist others with reference to Django 3.1/3.2/4.0:

  1. Go to your settings.py.

  2. Add in 'OPTIONS' the following:

    'undefined': jinja2.Undefined
    
  3. With this, undefined variables will not appear when rendered, i.e. be 'silent'. The full code should look something like this:

    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'DIRS': [
            BASE_DIR / 'templates-jinja2'
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'environment': 'config.jinja2.environment',
            'context_processors': [],
            'undefined': jinja2.DebugUndefined
    
        },
    },
    
  4. Alternatively, you can use DebugUndefined to see undefined variables, or 'StrictUndefined' to raise exceptions where undefined variables are used.

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