模版解析
tmpl, err := template.ParseFiles("layout.html")
if err != nil {
panic(err)
}
或者
tmpl := template.Must(template.ParseFiles("layout.html"))
以上代码可加载模版文件。
模版执行
func(w http.ResponseWriter, r *http.Request) {
tmpl.Execute(w, data)
}
请求执行代码运行时,模版会被写入响应体中,接口请求者会获得该内容。
完整代码
<h1>{{.PageTitle}}</h1>
<ul>
{{range .Todos}}
{{if .Done}}
<li class="done">{{.Title}}</li>
{{else}}
<li>{{.Title}}</li>
{{end}}
{{end}}
</ul>
package main
import (
"html/template"
"net/http"
)
type Todo struct {
Title string
Done bool
}
type TodoPageData struct {
PageTitle string
Todos []Todo
}
func main() {
tmpl := template.Must(template.ParseFiles("layout.html"))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
data := TodoPageData{
PageTitle: "My TODO list",
Todos: []Todo{
{Title: "Task 1", Done: false},
{Title: "Task 2", Done: true},
{Title: "Task 3", Done: true},
},
}
tmpl.Execute(w, data)
})
http.ListenAndServe(":8090", nil)
}