我在控制空白和仍然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 mainimport ( "os" "text/template")type View struct { layout string body string}type Smap map[string]stringfunc (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 angora3 items are made of wool </body></html>我想要的是:<!DOCTYPE html><html> <head> <title>stock</title> </head> <body>2 items are made of angora3 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}}
3 回答
手掌心
TA貢獻1942條經驗 獲得超3個贊
您可以使用空白控制器
{{range .foos -}} // eats trailing whitespace
<tr><td>do something</td></tr>
{{- end}} // eats leading whitespace (\n from previous line)
慕運維8079593
TA貢獻1876條經驗 獲得超5個贊
在這種情況下,空白對用戶瀏覽器的渲染輸出沒有影響,因此控制它在美學上沒有多大意義。
換句話說,您可以擁有格式良好的模板(我更喜歡)或部分格式良好的 HTML(無嵌套縮進)。選擇一個或使用任何現有的格式化程序對 HTML 進行后處理。
- 3 回答
- 0 關注
- 338 瀏覽
添加回答
舉報
0/150
提交
取消
