jinja2投掷TemplateSyntaxError:意外的char

时间:2018-03-18 01:22:04

标签: python templates dictionary jinja2

我正在向Jinja传递一个包含时间段字符串的数据集,例如“0Y-5Y”。标签是我的组织的标准,所以我不想改变它们。但是,该字符串导致Jinja抛出TemplateSyntaxError: unexpected char错误。

有人可以解释为什么会出现这种特殊错误,以及我如何解决它?

我看到from here带有空格字符的变量可能会引发类似的错误,但这不适用于我的情况。

似乎Jinja试图将字符串解析为数字?我以为这只是一个用作字典键的简单字符串?有没有办法强迫Jinja不要这样做,比如raw tags或类似的?

这是我的代码:

# 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 )

输出:

  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

1 个答案:

答案 0 :(得分:1)

在您访问数据中的单元格时,请尝试item['0Y-5Y']而不是item.0Y-5Y

html_ok = """
{% for item in data %}
  {{ item['name'] }}  {{ item['0Y-5Y'] }}
{% endfor %}
 """