Golang template range newline removal

别来无恙 提交于 2021-02-18 12:08:29

问题


I'm trying to figure out how I can remove the new lines in my template that are put there by the {{range}} and {{end}}. I get the following output without any of the "-" tags:

type {{makeGoTableName .TableName}} struct {
  {{range $key, $value := .TableData}}
    {{makeGoColName $value.ColName}} {{$value.ColType}} `db:"{{makeDBColName $value.ColName}}",json:"{{$value.ColName}}"`
  {{end}}
}

Results in:

type Dogs struct {

  ID int64 `db:"id",json:"id"`

  DogNumber int64 `db:"dog_number",json:"dog_number"`

}

If I add the - tags like so, I can get it close to desirable but it breaks the indentation of the final closing brace:

type {{makeGoTableName .TableName}} struct {
  {{range $key, $value := .TableData -}}
    {{makeGoColName $value.ColName}} {{$value.ColType}} `db:"{{makeDBColName $value.ColName}}",json:"{{$value.ColName}}"`
  {{end -}}
}

Results in:

type Dogs struct {
  ID int64 `db:"id",json:"id"`
  DogNumber int64 `db:"dog_number",json:"dog_number"`
  }

Any ideas?


回答1:


Its mostly on playing with the trailing slash, try

package main

import (
    "os"
    "text/template"
)

type myGreetings struct {
    Greet []string
}

func main() {
    const txt = `
{
        {{- range $index, $word := .Greet}}
  Hello {{$word -}}!!!
        {{- end}}
}
`
    greetText := myGreetings{
        Greet: []string{"World", "Universe", "Gophers"},
    }
    t := template.Must(template.New("Text").Parse(string(txt)))
    t.Execute(os.Stdout, greetText)

}

https://play.golang.org/p/eGm3d3IJPp

Output:

{
  Hello World!!!
  Hello Universe!!!
  Hello Gophers!!!
}


来源:https://stackoverflow.com/questions/35565915/golang-template-range-newline-removal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!