英文:
Golang template range newline removal
问题
我正在尝试弄清楚如何删除模板中由{{range}}和{{end}}添加的换行符。我得到的输出没有任何"- "标记:
type {{makeGoTableName .TableName}} struct {
{{range $key, $value := .TableData}}
{{makeGoColName $value.ColName}} {{$value.ColType}} `db:"{{makeDBColName $value.ColName}}",json:"{{$value.ColName}}"`
{{end}}
}
结果为:
type Dogs struct {
ID int64 `db:"id",json:"id"`
DogNumber int64 `db:"dog_number",json:"dog_number"`
}
如果我像这样添加"- "标记,我可以接近理想的效果,但它会破坏最后一个闭合大括号的缩进:
type {{makeGoTableName .TableName}} struct {
{{range $key, $value := .TableData -}}
{{makeGoColName $value.ColName}} {{$value.ColType}} `db:"{{makeDBColName $value.ColName}}",json:"{{$value.ColName}}"`
{{end -}}
}
结果为:
type Dogs struct {
ID int64 `db:"id",json:"id"`
DogNumber int64 `db:"dog_number",json:"dog_number"`
}
有什么想法吗?
英文:
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
得分: 23
主要是在处理尾随破折号的问题,尝试以下代码:
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)
}
输出结果:
{
Hello World!!!
Hello Universe!!!
Hello Gophers!!!
}
链接:https://play.golang.org/p/eGm3d3IJPp
英文:
Its mostly on playing with the trailing dash, 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!!!
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论