这是别人的博文http://blog.csdn.net/rufidmx/article/details/8644895
测试过了的,没有问题。对于t.Execute() 请各位查看源代码。
大概的意思就是讲数据写入实现了 io.writer的接口当中。
package main
import (
"fmt"
"html/template"
"net/http"
"os"
)
type Person struct {
Name string
Age int
Emails []string
Company string
Role string
}
type OnlineUser struct {
User []*Person
LoginTime string
}
func Handler(w http.ResponseWriter, r *http.Request) {
dumx := Person{
Name: "zoro",
Age: 27,
Emails: []string{"dg@gmail.com", "dk@hotmail.com"},
Company: "Omron",
Role: "SE"}
chxd := Person{Name: "chxd", Age: 27, Emails: []string{"test@gmail.com", "d@hotmail.com"}}
onlineUser := OnlineUser{User: []*Person{&dumx, &chxd}}
//t := template.New("Person template")
//t, err := t.Parse(templ)
t, err := template.ParseFiles("login.html")
checkError(err)
err = t.Execute(w, onlineUser)
checkError(err)
}
func main() {
http.HandleFunc("/", Handler)
http.ListenAndServe(":8888", nil)
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
os.Exit(1)
}
}
关键在于{{}}的处理,range是迭代的意思。
<html>
<head>
</head>
<body>
<form action="/test" method="POST">
{{with .User}}
{{range .}}
<input type="radio" name="test" value={{.Age}}/>{{.Age}}<br/>
{{end}}
{{end}}
<input type="submit" value="submit"/>
</form>
</body>
</html>
转载于:https://my.oschina.net/u/2609412/blog/601037