0

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
Roberto
  • 2,054
  • 4
  • 31
  • 46

1 Answers1

1

try item['0Y-5Y'] instead of item.0Y-5Y as you are accesing the cells in your data like:

html_ok = """
{% for item in data %}
  {{ item['name'] }}  {{ item['0Y-5Y'] }}
{% endfor %}
 """
Emre
  • 307
  • 1
  • 8
  • I had no idea that syntax was valid. I'll have to look into it a little more, but it worked with the toy program presented above. Thanks for the lead. – Roberto Mar 18 '18 at 14:24
  • I think it cannot just parse **item.0Y-5Y**. Try to define a variable in Python, like `0Y-5Y` or even `0Y5Y`, they fail. A variable/Attribute begining with 0 and a minus sign in it too? It won't like it ;) – Emre Mar 18 '18 at 17:23