{{.Title}}
{{.Content}}
{{if .Published}} 已发布 {{else}} 草稿 {{end}}使用html/template包渲染基本HTML模板。
package main
import (
"html/template"
"net/http"
)
type PageData struct {
Title string
Content string
}
func handler(w http.ResponseWriter, r *http.Request) {
// 解析模板
tmpl := template.Must(template.ParseFiles("templates/layout.html"))
// 准备数据
data := PageData{
Title: "首页",
Content: "欢迎访问我们的网站!",
}
// 渲染模板
tmpl.Execute(w, data)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
使用模板嵌套实现页面布局。
// layout.html
{{.Title}}
{{template "header" .}}
{{template "content" .}}
{{template "footer" .}}
// header.html
{{define "header"}}
{{.Title}}
{{end}}
// content.html
{{define "content"}}
{{.Content}}
{{end}}
// footer.html
{{define "footer"}}
{{end}}
使用自定义函数扩展模板功能。
package main
import (
"html/template"
"net/http"
"time"
)
func formatDate(t time.Time) string {
return t.Format("2006-01-02")
}
func main() {
// 创建函数映射
funcMap := template.FuncMap{
"formatDate": formatDate,
}
// 解析模板
tmpl := template.Must(template.New("").Funcs(funcMap).ParseFiles("templates/post.html"))
// 准备数据
data := struct {
Title string
Date time.Time
}{
Title: "Go语言学习",
Date: time.Now(),
}
// 渲染模板
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tmpl.Execute(w, data)
})
http.ListenAndServe(":8080", nil)
}
在模板中使用条件语句。
在模板中使用循环语句。
// template.html
{{.Title}}
{{.Title}}
{{range .Items}}
- {{.Name}} - {{.Price}}
{{end}}
ID
名称
价格
{{range $index, $item := .Items}}
{{$index}}
{{$item.Name}}
{{$item.Price}}
{{end}}