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

Go text/template多行字符串缩进问题:如何统一缩进层级?

解决Go text/template多行字符串缩进问题

当使用Go的text/template生成YAML时,多行字符串的子行无法自动继承模板变量所在层级的缩进,可通过以下两种方案解决:

方案1:自定义缩进函数(推荐)

自定义一个模板函数,对多行字符串的每一行添加指定数量的缩进,同时兼容空行处理:

package main

import (
    "os"
    "strings"
    "text/template"
)

// indent 为字符串的每一行添加n个空格缩进
func indent(n int, s string) string {
    indentStr := strings.Repeat(" ", n)
    lines := strings.Split(s, "\n")
    var result []string
    for _, line := range lines {
        if line != "" {
            result = append(result, indentStr+line)
        } else {
            result = append(result, line)
        }
    }
    return strings.Join(result, "\n")
}

func main() {
    // 注册自定义函数到模板
    funcMap := template.FuncMap{
        "indent": indent,
    }
    tpl := template.Must(template.New("yml").Funcs(funcMap).Parse(
        `routes:
{{ indent 2 . }}
`))

    value := `foo
bar`
    tpl.Execute(os.Stdout, value)
}

执行后输出符合预期:

routes:
  foo
  bar

方案2:简单替换换行符(适用于无空行场景)

如果不需要处理空行,可直接通过替换换行符快速实现缩进:

package main

import (
    "os"
    "strings"
    "text/template"
)

func main() {
    funcMap := template.FuncMap{
        "addLineIndent": func(s string) string {
            // 将换行符替换为"换行+2个空格"
            return strings.Replace(s, "\n", "\n  ", -1)
        },
    }
    tpl := template.Must(template.New("yml").Funcs(funcMap).Parse(
        `routes:
  {{ . | addLineIndent }}
`))

    value := `foo
bar`
    tpl.Execute(os.Stdout, value)
}

补充说明

Go标准库的text/template未内置多行缩进处理函数,因此需要自定义函数或借助第三方库(如Masterminds/sprig)实现。若项目允许依赖第三方库,可直接使用其提供的indent或nindent函数简化代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:00:26