变量使用了jinja2的内部呈现函数

2024-04-24 08:20:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个XML模板文件,需要使用jinja2用正确的值更新

例如:

<xyz controller-version="004-002-010-000">
    <abc>
        <name>**var_HR_EXACT_NAME**</name>
        <type>OPERATION</type>
     </abc>
</xyz>

要更改以粗体字母表示的变量的值吗

Python代码段:

app_import_dir=/usr/local/app/template
template_file_name=TemplateFileName.xml
temp_template_file=/usr/local/app/template/TemplateFileName.xml
property_variable_name='var_HR_EXACT_NAME'
property_variable='This is the new value'

env=jinja2.Environment(loader=jinja2.FileSystemLoader(app_import_dir))
raw_template=env.get_template(template_file_name)
final_template=raw_template.render( **property_variable_name** = **property_variable** )

with open(temp_template_file, 'w') as f:
    f.write(final_template)

注意:我在render函数中使用了两个变量,这将用null替换变量

但是当我在render中使用exect字符串时,它工作得很好。有人能帮我找到解决办法吗


Tags: nameappjinja2vartypehrtemplateproperty
1条回答
网友
1楼 · 发布于 2024-04-24 08:20:36

Answer:

看起来我们不应该在循环中使用render,因此我的python脚本使用了字典。 在字典中添加所有变量,并使用下面的命令一次性替换,它将按预期工作。你知道吗

代码片段:

#Create a new dictionary
view = {}

#Add all the variables from loop
view[property_variable_name] = property_variable

env=jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir))
raw_template=env.get_template(template_file_name)

#Call dictionary and replace all variable from template
final_template = raw_template.render(**view)

相关问题 更多 >