/root/code/go/src/contoso.org/hello/index.html
<!DOCTYPE html>
<html>
<head>
<title>模板中如何插入数据?</title>
<Meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<Meta name="keywords" content="关键词1,关键词2">
<Meta name="description" content="">
<style>
span {display:block;width:100px;float:left;}
</style>
</head>
<body>
<div>
<h3>输出嵌套字段内容</h3>
<p><b>{{.UserName}}</b><p>
<ul>
{{range .Emails}}
<li>{{.}}</li>
{{end}}
</ul>
<ul>
{{with .Friends}}
{{range .}}
<li><span>{{.Fname}}</span><span>{{.Age}}</span><span>{{.Mobile}}</span></li>
{{end}}
{{end}}
</ul>
</div>
</body>
</html>
/root/code/go/src/contoso.org/hello/main.go
package main
import (
"html/template"
"net/http"
)
type Friend struct {
Fname string
Age int
Mobile string
}
type Person struct {
UserName string
Emails []string
Friends []*Friend
}
func main() {
http.HandleFunc("/",load)
http.ListenAndServe(":9090",nil)
}
func load(w http.ResponseWriter,r *http.Request) {
tim := Friend{Fname: "Tim",Age: 25,Mobile: "13620052000"}
jack := Friend{Fname: "Jack",Age: 28,Mobile: "13520172000"}
tom := Friend{Fname: "Tom",Age: 19,Mobile: "13512345000"}
p := Person{UserName: "Jason",
Emails: []string{"jason@163.com","jason@hotmail.com"},
Friends: []*Friend{&tim,&jack,&tom}}
t,_ := template.ParseFiles("index.html")
t.Execute(w,p)
}
模板格式处理如下,注意这个神奇的“-”符号,它的位置可以写在花括号内部的前后:
<!DOCTYPE html>
<html>
<head>
<title>模板中如何插入数据?</title>
<Meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<Meta name="keywords" content="关键词1,关键词2">
<Meta name="description" content="">
<style>
span {display:block;width:100px;float:left;}
</style>
</head>
<body>
<div>
<h3>输出嵌套字段内容</h3>
<p><b>{{.UserName}}</b><p>
<ul>
{{range .Emails -}}
<li>{{.}}</li>
{{- end}}
</ul>
<ul>
{{with .Friends -}}
{{range . -}}
<li><span>{{.Fname}}</span><span>{{.Age}}</span><span>{{.Mobile}}</span></li>
{{- end}}
{{- end}}
</ul>
</div>
</body>
</html>
神奇的减号“-”,去掉Go Template生成的标签换行符:
<html>
<head>
<title>模板中如何插入数据?</title>
<Meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<Meta name="keywords" content="关键词1,关键词2">
<Meta name="description" content="">
<style>
span {display:block;width:100px;float:left;}
</style>
</head>
<body>
<div>
<h3>输出嵌套字段内容</h3>
<p><b>{{.UserName}}</b><p>
<ul>
{{- range .Emails}}
<li>{{.}}</li>
{{- end}}
</ul>
<ul>
{{- with .Friends}}
{{- range .}}
<li><span>{{.Fname}}</span><span>{{.Age}}</span><span>{{.Mobile}}</span></li>
{{- end}}
{{- end}}
</ul>
</div>
</body>
</html>
原文链接:https://www.f2er.com/go/188315.html