LoginSignup
13
9

More than 5 years have passed since last update.

html/templateでlayoutファイルとcontentsファイルを分けたい場合

Last updated at Posted at 2014-11-11

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 }}

特に、どこかのドキュメントにやり方が書いてあるわけじゃなかったので、
今の今まで気づきませんでした。

gist: https://gist.github.com/hiroosak/fe52f06895dc40f7030b

13
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
9