Наконец-то я заставил его работать, но только когда не следовал инструкциям.
Решение Часть 1
Пропустить {{define}} и {{end}} в шаблонах.Странно ...
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Go Web Programming</title>
</head>
<body>
layout level
{{ template "content" . }}
</body>
</html>
И в подшаблонах ...
<h1 style="color: red;">Page 1!</h1>
Часть решения 2
Я нашел фрагмент кодас AddParsTree, как упомянул Эли, и вот код (упрощенный без обработки ошибок)
package main
import (
"html/template"
"net/http"
"strings"
)
var tpl *template.Template
func init() {
tpl = template.Must(template.ParseGlob("templates/*.html"))
}
func main() {
http.HandleFunc("/", index)
http.ListenAndServe(":8080", nil)
}
func index(w http.ResponseWriter, r *http.Request) {
path := strings.Trim(r.URL.Path, "/")
switch path {
case "":
path = ("home.html")
default:
path = (path + ".html")
}
layout := tpl.Lookup("layout.html")
layout, _ = layout.Clone()
t := tpl.Lookup(path)
_, _ = layout.AddParseTree("content", t.Tree)
layout.Execute(w, "")
Я не очень понимаю, почему я должен не повиноваться руководствам, чтобы заставить его работать.Любые комментарии, которые просвещают меня, будут оценены.