简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM