package main
import (
"html/template"
"net/http"
"time"
)
type User struct {
Username, Password string
RegTime time.Time
}
//这个函数的名字要大写,要不然模板中无法调用这个函数
func ShowTime(t time.Time, format string) string {
return t.Format(format)
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
//这边有个地方值得注意,template.New()函数中参数名字要和ParseFiles()
//函数的文件名要相同,要不然就会报错:"" is an incomplete template
tmpl := template.New("demo.html")
tmpl = tmpl.Funcs(template.FuncMap{"showtime": ShowTime})
tmpl, _ = tmpl.ParseFiles("demo.html")
//mpl, _ = tmpl.Parse(`<p>{{.Username}}|{{.Password}}|{{.RegTime.Format "2006-01-02 15:04:05"}}</p>
//<p>{{.Username}}|{{.Password}}|{{showtime .RegTime "2006-01-02 15:04:05"}}</p>
//`)
// tmpl = template.Must(tmpl.ParseFiles("templates/demo.html")) // 这样写也可以的,那么这个template.Must到底干嘛的呢? 其实就是省略了一个err
user := User{"dotcoo", "dotcoopwd", time.Now()}
if err := tmpl.ExecuteTemplate(w, "demo.html", user); nil != err {
http.Error(w, err.Error(), http.StatusBadRequest)
}
})
http.ListenAndServe(":8082", nil)
}
<h1>Func</h1>
<p>{{.Username}}|{{.Password}}|{{.RegTime.Format "2006-01-02 15:04:05"}}</p>
<p>{{.Username}}|{{.Password}}|{{showtime .RegTime "2006-01-02 15:04:05"}}</p>
最终显示结果: