我希望使用Jinja2将模板存储为Python中的字符串变量,而不是作为文件进行渲染。我该如何操作?
例如,我想使用f-strings来达到这个目的:
很遗憾,f-strings不能满足我的需求,因此我想尝试一下Jinja2。 编辑: 要求
我想从这个字典中提取数值,将其插入模板并将其存储为字符串以便稍后使用。我尝试使用下面的代码,但是出现了无效语法错误。"最初的回答"
例如,我想使用f-strings来达到这个目的:
template = f""" This is a {foo}"""
很遗憾,f-strings不能满足我的需求,因此我想尝试一下Jinja2。 编辑: 要求
cars = {
'tesla': {
'cost': '34000',
'length': '185',
'range': '220',
},
'chevy': {
'cost': '37000',
'length': '134',
'range': '238',
}
我想从这个字典中提取数值,将其插入模板并将其存储为字符串以便稍后使用。我尝试使用下面的代码,但是出现了无效语法错误。"最初的回答"
template1 = Template("""Tesla
Cost : {{ cars.tesla.cost }}""")
template2 = template1.render()
# Expected Output
print(template2)
Tesla
Cost : 34000