【问题标题】:Variable uses inside render function of jinja2jinja2的render函数内部变量使用
【发布时间】:2017-10-12 13:06:48
【问题描述】:

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

例如:

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

想改变粗体字的变量的值

Python代码sn-p:

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)

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

但是当我在渲染中使用执行字符串时,它可以正常工作。有人可以帮我找到解决方案吗?

【问题讨论】:

    标签: python jinja2


    【解决方案1】:

    答案:

    看起来我们不应该在循环内使用渲染,因此使用字典推进了我的 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)
    

    【讨论】:

    • 确保渲染在循环之外
    猜你喜欢
    • 2019-07-08
    • 2014-10-22
    • 2018-09-11
    • 2016-10-23
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 2019-12-12
    相关资源
    最近更新 更多