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

如何在Django模板(DTL)中用内置功能为多变量添加间隔符?

Great question! You can absolutely solve this using Django's built-in template features without writing custom filters or tags. Here are two clean approaches:

Approach 1: Concise Filter Chain

This method uses string concatenation and built-in filters to clean up unwanted separators:

<div>
  {{ person.name|default:""|add:" · "|add:person.phone|default:""|add:" · "|add:person.city|default:""|replace:" ·  · ":" · "|rstrip:" · "|lstrip:" · " }}
</div>

How it works:

  • default:"" replaces any None values with empty strings to avoid "None" appearing in the output.
  • add:" · " appends the separator to each value.
  • replace:" · · ":" · " fixes cases where a middle variable is empty (e.g., turns "John · · New York" into "John · New York").
  • rstrip:" · " and lstrip:" · " remove any leading or trailing separators if the first or last variable is empty.

Approach 2: Explicit Conditional Statements

If you prefer more readable code (especially when working with more variables), use nested {% if %} tags to conditionally add separators only when needed:

<div>
  {% if person.name %}{{ person.name }}{% endif %}
  {% if person.phone %}
    {% if person.name %} · {% endif %}{{ person.phone }}
  {% endif %}
  {% if person.city %}
    {% if person.name or person.phone %} · {% endif %}{{ person.city }}
  {% endif %}
</div>

How it works:

  • We first render the name if it exists.
  • For the phone number, we add a separator only if the name was rendered.
  • For the city, we add a separator only if either the name or phone number was rendered.

This approach is more verbose but makes the logic crystal clear, which is helpful if you need to extend it to more variables later.

Both methods will give you exactly the behavior you want: separators only between non-empty values, no trailing or leading dots.

内容的提问来源于stack exchange,提问作者Yannic Hamann

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:04:50