问题
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