priestc
priestc

Reputation: 35280

Multiple renders of jinja2 templates?

Is there any way to do this with jinja2?

template = Template("{{ var1 }}{{ var2 }}")
rendered1 = template.render(var1=5) # "5-{{ var2 }}"
rendered2 = Template(rendered1).render(var2=6) # "5-6"

basically, I want to be able to do multiple passes on a template. When the template engine finds a variable in the template that is not in the context, instead of replacing it with nothing, keep the template variable intact? If not jinja2, is there any other python template library that can do this?

Upvotes: 17

Views: 4937

Answers (1)

Pedro Romano
Pedro Romano

Reputation: 11213

You can use DebugUndefined, which keeps the failed lookups, as your Undefined Type for the undefined parameter of the Template environment:

>>> from jinja2 import Template, DebugUndefined
>>> template = Template("{{ var1 }}-{{ var2 }}", undefined=DebugUndefined)
>>> rendered1 = template.render(var1=5) # "5-{{ var2 }}"
>>> print(rendered1)
5-{{ var2 }}
>>> rendered2 = Template(rendered1).render(var2=6) # "5-6"
>>> print(rendered2)
5-6

Upvotes: 14

Related Questions