我在控制空白和仍然html/template
以可读方式格式化模板时遇到问题。我的模板看起来像这样:
布局.tmpl
{{define "layout"}}
<!DOCTYPE html>
<html>
<head>
<title>{{.title}}</title>
</head>
<body>
{{ template "body" . }}
</body>
</html>
{{end}}
正文.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",
},
},
})
}
但这会产生(注意:文档类型上方有一行):
<!DOCTYPE html>
<html>
<head>
<title>stock</title>
</head>
<body>
2 items are made of angora
3 items are made of wool
</body>
</html>
我想要的是:
<!DOCTYPE html>
<html>
<head>
<title>stock</title>
</head>
<body>
2 items are made of angora
3 items are made of wool
</body>
</html>
在其他模板语言中,我可以说类似
[[- value -]]
并且动作前后的空格被剥离,但我在html/template
. 这真的意味着我必须像下面这样使我的模板不可读吗?
布局.tmpl
{{define "layout"}}<!DOCTYPE html>
<html>
<head>
<title>.title</title>
</head>
<body>
{{ template "body" . }} </body>
</html>
{{end}}
正文.tmpl
{{define "body"}}{{ range .items }}{{.count}} items are made of {{.material}}
{{end}}{{end}}