我遇到了控制空白的问题,仍然以可读的方式格式化html/template模板。我的模板看起来财产以后这样的:如何在HTML /模板中的操作后控制空白?
layout.tmpl
{{define "layout"}}
{{.title}}{{ template "body" . }}
{{end}}
body.tmpl
{{define "body"}}
{{ range .items }}
{{.count}} items are made of {{.material}}
{{end}}
{{end}}
代码
package main
import (
"os"
"text/template"
)
type View struct {
layout string
body string
}
type Smap map[string]string
func (self View) Render(data map[string]interface{}) {
layout := self.layout + ".tmpl"
body := self.body + ".tmpl"
tmpl := template.Must(template.New("layout").ParseFiles(layout, body))
tmpl.ExecuteTemplate(os.Stdout, "layout", data)
}
func main() {
view := View{ "layout", "body" }
view.Render(map[string]interface{}{
"title": "stock",
"items": []Smap{
Smap{
"count": "2",
"material": "angora",
},
Smap{
"count": "3",
"material": "wool",
},
},
})
}
但产生(注:上面有一条线文档类型):
stock2 items are made of angora
3 items are made of wool
我要的是:
stock2 items are made of angora
3 items are made of wool
在其他的模板语言,我可以说这样的话
[[- value -]]
前和作用后的空白被剥离,但我看不到任何东西像html/template那样。这是否意味着我必须使我的模板不可读取,如下所示?
layout.tmpl
{{define "layout"}}
.title{{ template "body" . }}
{{end}}
body.tmpl
{{define "body"}}{{ range .items }}{{.count}} items are made of {{.material}}
{{end}}{{end}}