如何 trim Go 模板中的空行?

How to trim empty rows in Go templates?

go版本go1.16.3windows/amd64

我使用 template/html 包。如果我将变量设置为 html,

例子

  {{range $kk, $vv := .Users -}}
      {{if eq $vv.Id $performedBy}}
          {{$pSurname = $vv.ContactData.Surname}} {{$pName = $vv.ContactData.Name}}
      {{- end}}
  {{- end}}

每当我在一个范围内填充一个变量时,它会给我写一个空行。我能做些什么来防止这种情况再次发生?

text/template, Text and spaces:

的打包文件

By default, all text between actions is copied verbatim when the template is executed. [...]

However, to aid in formatting template source code, if an action's left delimiter (by default "{{") is followed immediately by a minus sign and white space, all trailing white space is trimmed from the immediately preceding text. Similarly, if the right delimiter ("}}") is preceded by white space and a minus sign, all leading white space is trimmed from the immediately following text. In these trim markers, the white space must be present: "{{- 3}}" is like "{{3}}" but trims the immediately preceding text, while "{{-3}}" parses as an action containing the number -3.

TLDR; 模板中的所有(白色)space 在操作之间保留。如果您不想要它们,您可以在开始分隔符之后或结束分隔符之前使用减号 - 将动作“就位”到 trim 前导或尾随白色 spaces.

您必须按照您想要的输出方式缩进模板,或使用 - 符号 trim 格式缩进。

您的 {{if}} 操作的主要问题:

  {{if eq $vv.Id $performedBy}}
      {{$pSurname = $vv.ContactData.Surname}} {{$pName = $vv.ContactData.Name}}
  {{- end}}

{{if}}的结束分隔符后有一个换行符,如果执行{{if}}的正文,它将被保留。 - 登录 {{- end}} 仅 trim 在此 {{- end}} 之前的换行符(变量赋值之后的换行符),而不是 [=17 末尾的换行符=].

例如使用此模板:

const src = `{{$performedBy := "1"}}{{$pSurname := ""}}{{$pName := "" -}}
{{range $kk, $vv := .Users -}}
User idx: {{$kk}}
{{if eq $vv.Id $performedBy -}}
    {{- $pSurname = $vv.ContactData.Surname -}} {{- $pName = $vv.ContactData.Name -}}
{{- end -}}
{{- end}}`

正在测试:

type CData struct {
    Surname, Name string
}

type User struct {
    Id          string
    ContactData CData
}

func main() {
    t := template.Must(template.New("").Parse(src))

    p := map[string]interface{}{
        "Users": []User{
            {Id: "1", ContactData: CData{"Foo", "Bar"}},
            {Id: "2", ContactData: CData{"Foo2", "Bar2"}},
            {Id: "1", ContactData: CData{"Foo3", "Bar3"}},
            {Id: "4", ContactData: CData{"Foo4", "Bar4"}},
        },
    }

    if err := t.Execute(os.Stdout, p); err != nil {
        panic(err)
    }
}

输出(在 Go Playground 上尝试):

User idx: 0
User idx: 1
User idx: 2
User idx: 3