Last active
April 21, 2018 08:44
-
-
Save hiroosak/fe52f06895dc40f7030b to your computer and use it in GitHub Desktop.
html/template で layoutファイルとcontentファイルを分けたい場合
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{ define "content" }} | |
<p>Hello {{ .Name }}</p> | |
{{ end }} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> | |
</head> | |
<body> | |
{{ template "content" . }} | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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