Jinja2渲染模板忽略没有值的字段

2024-09-25 00:34:11 发布

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

我有一个default.yaml,它有如下属性:

app_conf:
   port: 443
   ping_port: 444

我有一个application.conf,它看起来像:

...
master_port "{{ app_conf.port }}";
pingcheck_port "{{ app_conf.ping_port }}";
...

我使用下面的python代码将application.conf中的字段替换为default.yaml中的字段

configuration = yaml.load(open('conf/default.yaml'))['app_conf']
template = env.get_template("application.conf")
confReplaceOutput = template.render(app_conf=configuration)

现在,如果default.yaml文件中没有{app\u conf.ping\u port}的值,则呈现的输出是:

    pingcheck_port:;

我希望输出是

pingcheck_port "{{ app_conf.ping_port }}";

那么,如何配置jinja2来忽略对yaml文件中没有定义的字段的替换呢


Tags: 文件代码masterappdefaultyaml属性application
1条回答
网友
1楼 · 发布于 2024-09-25 00:34:11

我会用if,else和原始块

{% if app_conf is defined and app_conf.ping_port is defined -%}
    pingcheck_port "{{ app_conf.ping_port }}";
{% else %}
    {%raw-%}
        pingcheck_port "{{ app_conf.ping_port }}";
    {%endraw%}
{% endif %}

相关问题 更多 >