[TOC] ## 简单 demo ``` //go type HomePage struct { Name string } func HomeHandler(w http.ResponseWriter, r *http.Request) { p := &HomePage{Name: "avenssi"} t, e := template.ParseFiles(TEMPLATE_PATH + "/home.html") if e != nil { log.Printf("Parsing template home.html error:%s", e) } t.Execute(w, p) } //html <a href="#news">{{.Name}}</a> ``` ## 模板说明 ``` //go data := TodoPageData{ PageTitle: "My TODO list", Todos: []Todo{ {Title: "Task 1", Done: false}, {Title: "Task 2", Done: true}, {Title: "Task 3", Done: true}, }, } //html <h1>{{.PageTitle}}<h1> <ul> {{range .Todos}} {{if .Done}} <li class="done">{{.Title}}</li> {{else}} <li>{{.Title}}</li> {{end}} {{end}} </ul> ```` ## ExecuteTemplate 模板中有多个定义 login.html ``` {{define "/user/login1"}} <body> login1 </body> {{end}} {{define "/user/login2"}} <body> login2 </body> {{end}} ``` go ``` http.HandleFunc("/user/login", func(w http.ResponseWriter, r *http.Request) { tpl, e := template.ParseFiles("login.html") if e != nil { log.Fatal(e.Error()) } tpl.ExecuteTemplate(w,"/user/login1",nil) }) ```