Cha*_*ens 7 whitespace templates go go-html-template
我有一个控制空白的问题,仍然html/template以可读的方式格式化模板.我的模板看起来像这样:
layout.tmpl
{{define "layout"}}
<!DOCTYPE html>
<html>
<head>
<title>{{.title}}</title>
</head>
<body>
{{ template "body" . }}
</body>
</html>
{{end}}
Run Code Online (Sandbox Code Playgroud)
body.tmpl
{{define "body"}}
{{ range .items }}
{{.count}} items are made of {{.material}}
{{end}}
{{end}}
Run Code Online (Sandbox Code Playgroud)
码
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",
},
},
})
}
Run Code Online (Sandbox Code Playgroud)
但这会产生(注意:doctype上方有一行):
<!DOCTYPE html>
<html>
<head>
<title>stock</title>
</head>
<body>
2 items are made of angora
3 items are made of wool
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我想要的是:
<!DOCTYPE html>
<html>
<head>
<title>stock</title>
</head>
<body>
2 items are made of angora
3 items are made of wool
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
在其他模板语言中,我可以说像
[[- value -]]
Run Code Online (Sandbox Code Playgroud)
并且在动作之前和之后的空白都被剥离了,但是我没有看到类似的东西html/template.这是否真的意味着我必须让我的模板不可读如下?
layout.tmpl
{{define "layout"}}<!DOCTYPE html>
<html>
<head>
<title>.title</title>
</head>
<body>
{{ template "body" . }} </body>
</html>
{{end}}
Run Code Online (Sandbox Code Playgroud)
body.tmpl
{{define "body"}}{{ range .items }}{{.count}} items are made of {{.material}}
{{end}}{{end}}
Run Code Online (Sandbox Code Playgroud)
hku*_*kci 10
你可以使用白色空间控制器
{{range .foos -}} // eats trailing whitespace
<tr><td>do something</td></tr>
{{- end}} // eats leading whitespace (\n from previous line)
Run Code Online (Sandbox Code Playgroud)
是的,空白和线条是按字面翻译的。如果您的一行仅包含 {{ Define }} 或任何其他不产生输出的内容,则解析的文件中将有一个空行。
理想情况下,因为您使用的是模板,所以您不需要查看或编辑解析的输出。作为参考,请使用 JSP/JSF 并查看它提供的丑陋输出。查看网上大多数页面的源代码,它们也很难看。
祝你好运!
| 归档时间: |
|
| 查看次数: |
5037 次 |
| 最近记录: |