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

Go text/template渲染Markdown列表时{{- }}过度修剪空格如何解决

解决方案

方法1:调整空白修剪位置(无需修改Go逻辑,仅修改模板)

你遇到的问题是{{- if开头的减号会修剪掉if标签前面所有的空白字符(包含标题后的换行),导致标题和第一个列表项直接拼接。只需要调整减号的位置,仅修剪条件不成立时产生的多余空行,保留标题后的换行即可。

修改后的模板代码示例:

tmplStr := `
# Debug Template 1

{{ if .ItemA }}- Item A: {{ .ItemA }}
{{ end -}}
{{ if .ItemB }}- Item B: {{ .ItemB }}
{{ end -}}
{{ if .ItemC }}- Item C: {{ .ItemC }}
{{ end -}}
{{ if .ItemD }}- Item D: {{ .ItemD }}
{{ end -}}
{{ if .ItemE }}- Item E: {{ .ItemE }}
{{ end }}

# Debug Template 2


{{ if .ItemA }}- Item A: {{ .ItemA }}
{{ end -}}
{{ if .ItemB }}- Item B: {{ .ItemB }}
{{ end -}}
{{ if .ItemC }}- Item C: {{ .ItemC }}
{{ end -}}
{{ if .ItemD }}- Item D: {{ .ItemD }}
{{ end -}}
{{ if .ItemE }}- Item E: {{ .ItemE }}
{{ end }}
`

渲染后完全符合预期输出:

# Debug Template 1

- Item A: Apple
- Item C: Cocola
- Item E: Ellie

# Debug Template 2


- Item A: Apple
- Item C: Cocola
- Item E: Ellie

方法2:使用range遍历(适合列表条目较多的场景)

如果后续列表条目会持续新增,可以把列表项配置预先封装为切片,在模板中遍历渲染,逻辑更简洁易维护:

Go代码调整

// 构造列表项配置,传入模板
data := struct {
    ItemA string
    ItemB string
    ItemC string
    ItemD string
    ItemE string
    Items []struct{Label, Value string}
}{
    ItemA: "Apple",
    ItemC: "Cocola",
    ItemE: "Ellie",
}
data.Items = []struct{Label, Value string}{
    {"Item A", data.ItemA},
    {"Item B", data.ItemB},
    {"Item C", data.ItemC},
    {"Item D", data.ItemD},
    {"Item E", data.ItemE},
}

对应模板

# Debug Template 1

{{ range .Items }}
{{- if .Value }}- {{ .Label }}: {{ .Value }}
{{ end -}}
{{ end }}

内容的提问来源于stack exchange,提问作者Phil Li

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:45:03