html/templateで、よくあるテンプレートエンジンのように、
コンテンツファイルとレイアウトファイルを分けたい(jadeでいうextendみたいなやつ)時があるけれど、
その場合はどうも ParseFiles関数を使えばそれっぽくなる。
main.go(一部)
func main() {
http.HandleFunc("/", handler)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
data := map[string]string{
"Name": "Mike",
}
tmpl := template.Must(template.ParseFiles("layout.html", "content.html"))
w.Header().Set("Content-Type", "text/html")
err := tmpl.Execute(w, data) // Hello, Mike
if err != nil {
panic(err)
}
}
layout.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
{{ template "content" . }}
</body>
</html>
content.html
{{ define "content" }}
<p>Hello, {{ .Name }}</p>
{{ end }}
特に、どこかのドキュメントにやり方が書いてあるわけじゃなかったので、
今の今まで気づきませんでした。