Search code examples
pythonjinja2undefined

Keep undefined variables


I am interested in rendering a template in multiple steps or keeping the tags for the undefined variables in Jinja2. I believe this would mean not only creating the 'UndefinedSilent" class (so the template won't crash on missing data) but also keeping the tags with the appropriate variable names if they are missing.

Example: Let's say we have the name = "Test" included in the context, but quantity is missing.

Givent the following template:

<p>{{name}} has {{quantity}}</p>

After rendering, I need the template to become:

<p>test has {{quantity}}</p>

Does anyone know if this is achievable?


Solution

  • Providing DebugUndefined to named parameter undefined in the env, apparently does the trick. The rendered template preserves the {{<undefined variable}}.

    Like here:

    from jinja2 import Environment, BaseLoader, DebugUndefined
    
    rtemplate = Environment(loader=BaseLoader,undefined=DebugUndefined).from_string("{{ a }} is defined, but {{ b}} is undefined")
    print(rtemplate.render({"a":"a"}))
    

    The result is:

    a is defined, but {{ b }} is undefined