raise an exception in jinja if we passed in a variable that is not present in the template

前端 未结 3 1851
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 16:21

Is there a method for jinja2 to raise an exception when we pass a variable that is not present in the template?

PS: This is different(or opposite) from raising an except

相关标签:
3条回答
  • 2021-02-01 16:24

    You can also do that:

    from jinja2 import Template, StrictUndefined
    Template('name: {{ name }} , city: {{ city }}',undefined=StrictUndefined).render(**{"name":"maoz","city":"aaa"})
    
    0 讨论(0)
  • 2021-02-01 16:27

    Maybe this could help you https://jinja.palletsprojects.com/en/2.11.x/api/#the-meta-api

    >>> from jinja2 import Environment, meta
    >>> env = Environment()
    >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
    >>> meta.find_undeclared_variables(ast)
    set(['bar'])
    
    0 讨论(0)
  • 2021-02-01 16:39

    When you load your jinja2.Environment, set the 'undefined' parameter to 'jinja2.StrictUndefined', e.g.:

    env = jinja2.Environment(loader=<someloader>, undefined=jinja2.StrictUndefined)
    

    You can catch and examine the render exception to see what was missing

    EDIT It would help if I read your full question. :)

    0 讨论(0)
提交回复
热议问题