如何在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 anyNonevalues 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:" · "andlstrip:" · "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

