Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple renders of jinja2 templates?

Tags:

python

jinja2

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?

like image 955
priestc Avatar asked Oct 21 '12 00:10

priestc


People also ask

Which 3 features are included in the Jinja2 templates?

Some of the features of Jinja are: sandboxed execution. automatic HTML escaping to prevent cross-site scripting (XSS) attacks. template inheritance.

What is the difference between Jinja and Jinja2?

from_string . Jinja 2 provides a Template class that can be used to do the same, but with optional additional configuration. Jinja 1 performed automatic conversion of bytes in a given encoding into unicode objects.


1 Answers

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
like image 124
Pedro Romano Avatar answered Sep 19 '22 14:09

Pedro Romano