2017-10-12 43 views
0

我有需要用正確的價值Jinja2的更新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) 

注:我使用的兩個變量裏面的渲染功能,這將替換爲空的變量

但是,當我使用Exec字符串內渲染它工作正常。誰能幫我找到了解決方案,請

回答

0

答:

看起來我們不應該使用內循環渲染,因此使用字典進步我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) 
+0

確保選中渲染是循環的外 –