如何在Jinja2中消除括号的歧义

时间:2019-04-16 16:18:09

标签: python jinja2

在Jinja2中区分括号的最简单方法是什么?以下是示例模板{{{ x }}},如果{foo},我想将其渲染为x="foo"

>>> import jinja2
>>> t = jinja2.Template('{{{ x }}}')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\app\python\anaconda\2\lib\site-packages\jinja2\environment.py", line 945, in __new__
    return env.from_string(source, template_class=cls)
  File "c:\app\python\anaconda\2\lib\site-packages\jinja2\environment.py", line 880, in from_string
    return cls.from_code(self, self.compile(source), globals, None)
  File "c:\app\python\anaconda\2\lib\site-packages\jinja2\environment.py", line 591, in compile
    self.handle_exception(exc_info, source_hint=source_hint)
  File "c:\app\python\anaconda\2\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "<unknown>", line 1, in template
jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}'

以下代码有效,但看起来确实很hacky:

>>> t = jinja2.Template('{{"{"}}{{ x }}{{"}"}}')
>>> t.render(x='foo')
u'{foo}'

0 个答案:

没有答案