昨日のコードをそのまま編集します。
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Template!</title>
</head>
<body>
<h1>Hello Template!</h1>
<div>
私の名前は {{.Name}} です。
</div>
</body>
</html>
go
package helloworld
import (
"net/http"
"html/template"
)
func init() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("app/template.html")
if err == nil {
contents := make(map[string]string, 1)
contents["Name"] = "y.okano"
t.Execute(w, contents)
}
})
}
構造体やマップを作って template.Execute() に渡すと該当する変数を探して展開してくれます。