I am passing Jinja a dataset that includes time-bucket strings like "0Y-5Y". The tags are standard to my organization, so I prefer not to change them. However, the string is causing Jinja to throw a TemplateSyntaxError: unexpected char
error.
Can someone please explain why this particular error arises, and how I can get around it?
I see from here that variables with space characters might throw similar error, but that does not apply in my case.
It seems almost like Jinja is trying to parse the string as a number? I thought it was just a simple string used as the dictionary key? Is there a way to force Jinja not to do this, like with raw tags or similar?
Here is my code:
# https://realpython.com/blog/python/primer-on-jinja-templating/#flask-examples
from jinja2 import Template
data = [
{'name':'aaa','0Y-5Y':100,'5Y-25Y':50,'total':150}
,{'name':'bbb','0Y-5Y':10,'5Y-25Y':125,'total':135}
]
html_ok = """
{% for item in data %}
{{ item.name }} {{ item.total }}
{% endfor %}
"""
html_error = """
{% for item in data %}
{{ item.name }} {{ item.0Y-5Y }}
{% endfor %}
"""
t=Template(html_ok)
print t.render( data=data )
t=Template(html_error)
print t.render( data=data )
And the output:
aaa 150
bbb 135
Traceback (most recent call last):
File "C:\Users\beRto\Desktop\jinja_number_key.py", line 23, in <module>
t=Template(html_error)
File "C:\Python27\lib\site-packages\jinja2-2.9.5-py2.7.egg\jinja2\environment.py", line 945, in __new__
return env.from_string(source, template_class=cls)
File "C:\Python27\lib\site-packages\jinja2-2.9.5-py2.7.egg\jinja2\environment.py", line 880, in from_string
return cls.from_code(self, self.compile(source), globals, None)
File "C:\Python27\lib\site-packages\jinja2-2.9.5-py2.7.egg\jinja2\environment.py", line 591, in compile
self.handle_exception(exc_info, source_hint=source_hint)
File "C:\Python27\lib\site-packages\jinja2-2.9.5-py2.7.egg\jinja2\environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "<unknown>", line 3, in template
TemplateSyntaxError: unexpected char u'Y' at 51