Skip to content

Instantly share code, notes, and snippets.

@hiroosak
Last active April 21, 2018 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiroosak/fe52f06895dc40f7030b to your computer and use it in GitHub Desktop.
Save hiroosak/fe52f06895dc40f7030b to your computer and use it in GitHub Desktop.
html/template で layoutファイルとcontentファイルを分けたい場合
{{ define "content" }}
<p>Hello {{ .Name }}</p>
{{ end }}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
{{ template "content" . }}
</body>
</html>
package main
import (
"html/template"
"log"
"net/http"
)
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)
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment