Skip to main content
 首页 » 编程设计

python之如何在 jinja2 的模板变量中使用特殊字符

2025年05月04日97xiaohuochai

我有一个要求,我想渲染包含 "."、".."、"/" 和 的值>"//" 在 jinja2 中。

例如我有一本字典:

values= {'pre_package_information[1]/comment': 'Device: 14.2', 'post_package_information[1]/comment': 'Device: 14.2-2'} 

现在我使用 jinja 渲染这个值:

mssg= "Test Succeeded!! Checking Device version for 14.2 release {{pre_package_information[1]/comment}}" 
jinja2.Template(mssg).render(values) 

但是报错:

jinja2.exceptions.UndefinedError: 'pre_package_information' is undefined 

看起来它没有在模板中使用 "[" 和 "/"。如何传递这些特殊字符。我还遇到了其他字符的问题,例如 "." 和 ".."

请您参考如下方法:

Jinja 要求所有顶级名称都是有效的 Python 标识符;查看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_]*.

要么提供符合该要求的标识符,要么将您的字典包装在另一个字典中以间接在其中查找您的键:

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) 

请注意,此处 values 字典作为关键字参数传入,因此它可以作为模板中的 values 访问。

演示:

>>> 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'