You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jinja单行If语句空白修剪:寻求更紧凑的模板实现方案

Jinja模板优化:更紧凑的条件列表写法

我想创建这样的Jinja模板:

Some list:
    - foo
    {% if a %}- bar: a{% endif %}
    {% if b %}- baz: b{% endif %}
    - quux

需要实现以下渲染效果——当变量a和/或b为False时,不会出现空行或多余空白。目前我能写出的最优版本是:

Some list:
    - foo
    {%- if a %}
    - bar: a
    {%- endif %}
    {%- if b %}
    - baz: b
    {%- endif %}
    - quux

请问有没有比这更紧凑的模板写法?

渲染目标

  • 当传入{ 'a': True, 'b': True }时,输出:
Some list:
    - foo
    - bar: a
    - baz: b
    - quux
  • 当传入{ 'a': True, 'b': False }时,输出:
Some list:
    - foo
    - bar: a
    - quux
  • 当传入{ 'a': False, 'b': True }时,输出:
Some list:
    - foo
    - baz: b
    - quux
  • 当传入{ 'a': False, 'b': False }时,输出:
Some list:
    - foo
    - quux

几种更紧凑的实现方案

1. 控制语句与列表项同行

把条件判断和列表内容放在同一行,用{%- %}消除左侧多余空白,既减少模板行数,又避免空行:

Some list:
    - foo
    {%- if a %}    - bar: a{% endif %}
    {%- if b %}    - baz: b{% endif %}
    - quux

2. 列表拼接式写法(适合扩展)

如果后续可能新增更多条件项,先构建列表再渲染会更清晰,维护性更强:

Some list:
{% set items = ['    - foo'] %}
{%- if a %}{% do items.append('    - bar: a') %}{% endif %}
{%- if b %}{% do items.append('    - baz: b') %}{% endif %}
{%- do items.append('    - quux') %}
{{ items|join('\n') }}

注意:使用do语句需要启用Jinja的jinja2.ext.do扩展。

3. 三元表达式极简写法

用Jinja的三元表达式直接输出内容或空字符串,无需额外控制标签,写法最紧凑:

Some list:
    - foo
    {{ '    - bar: a' if a else '' }}
    {{ '    - baz: b' if b else '' }}
    - quux

内容的提问来源于stack exchange,提问作者Scott Colby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 04:10:20