我遇到了控制空白的問題,仍然以可讀的方式格式化html/template
模板。我的模板看起來財產以後這樣的:如何在HTML /模板中的操作後控制空白?
layout.tmpl
{{define "layout"}}
<!DOCTYPE html>
<html>
<head>
<title>{{.title}}</title>
</head>
<body>
{{ template "body" . }}
</body>
</html>
{{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",
},
},
})
}
但產生(注:上面有一條線文檔類型):
<!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
那樣。這是否意味着我必須使我的模板不可讀取,如下所示?
layout.tmpl
{{define "layout"}}<!DOCTYPE html>
<html>
<head>
<title>.title</title>
</head>
<body>
{{ template "body" . }} </body>
</html>
{{end}}
body.tmpl
{{define "body"}}{{ range .items }}{{.count}} items are made of {{.material}}
{{end}}{{end}}
自走'1.6' https://golang.org/doc/go1.6#template – webwurst
是,1.6之前謝謝@webwurst,你可以檢查HTTPS ://golang.org/pkg/text/template/#hdr-Text_and_spaces – hkulekci
這隻適用於'text/template',而不是'html/template'。 –