Reputation: 683
I have a requirement where I want to render values containing "."
, ".."
, "/"
and "//"
in jinja2.
For example I have a dictionary :
values= {'pre_package_information[1]/comment': 'Device: 14.2', 'post_package_information[1]/comment': 'Device: 14.2-2'}
Now I am rendering this value using jinja:
mssg= "Test Succeeded!! Checking Device version for 14.2 release {{pre_package_information[1]/comment}}"
jinja2.Template(mssg).render(values)
But it is giving error:
jinja2.exceptions.UndefinedError: 'pre_package_information' is undefined
Looks like it is not taking "["
and "/"
in templates. How to pass these special characters. I faced problems with other characters also like "."
and ".."
Upvotes: 1
Views: 9334
Reputation: 1121316
Jinja requires that all top-level names are valid Python identifiers; see the Notes on identifiers section:
Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to match
[a-zA-Z_][a-zA-Z0-9_]*
.
Either provide identifiers that match that requirement, or wrap your dictionary in another to indirectly look up your keys in that:
values = {'pre_package_information[1]/comment': 'Device: 14.2', 'post_package_information[1]/comment': 'Device: 14.2-2'}
mssg= ("Test Succeeded!! Checking Device version for 14.2 release "
"{{values['pre_package_information[1]/comment']}}")
jinja2.Template(mssg).render(values=values)
Note that here the values
dictionary is passed in as a keyword argument, so it'll be accessible as values
in the template.
Demo:
>>> import jinja2
>>> values = {'pre_package_information[1]/comment': 'Device: 14.2', 'post_package_information[1]/comment': 'Device: 14.2-2'}
>>> mssg= ("Test Succeeded!! Checking Device version for 14.2 release "
... "{{values['pre_package_information[1]/comment']}}")
>>> jinja2.Template(mssg).render(values=values)
u'Test Succeeded!! Checking Device version for 14.2 release Device: 14.2'
Upvotes: 4
Reputation: 6978
The way you access the variable in the template needs to be like this
{{ values['pre_package_information[1]/comment'] }}
and call the render like render(values=values)
Just like in python you cannot have variables with special characters
Upvotes: 2