【问题标题】:How to Make Rendering Fail if Object has no Attribute?如果对象没有属性,如何使渲染失败?
【发布时间】:2022-11-14 20:33:50
【问题描述】:

如果对象obj 没有属性foo,那么我想在Jinja2 模板中引用{{obj.foo}} 以在渲染时失败。

目前我正在获取带有空变量的模板文本。如何获得标准的AttributeError 异常?

示例代码如下所示:

class Foo:
    pass
  
env = Environment(
        loader=PackageLoader("mydistro"),
        autoescape=select_autoescape()
    )   

t = env.get_template("template/path/to.j2")
print(t.render(obj=Foo()))

【问题讨论】:

    标签: python jinja2


    【解决方案1】:

    使用StrictUndefined 作为undefined 类初始化您的环境。

    env = Environment(
        loader=PackageLoader("mydistro"),
        autoescape=select_autoescape(),
        undefined=StrictUndefined,
    )   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      • 2011-10-14
      • 2020-11-01
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多