我正在将一个结构传递给嵌套模板,并尝试根据该结构中的字段呈现另一个模板。
func myHandler(w http.ResponseWriter, r *http.Request) {
allContent := getContent()
response := []struct {
Title string
Content []Content
Form string
}{
{"BIG TITLE, allContent.bigContent, "big_form"},
{"SMALL TITLE, allContent.smallContent, "small_form"},
}
t, err := template.ParseFiles("content.html", "big_form.html", "small_form.html")
if err != nil {
log.Printf("Failed to parse template: %v", err)
}
if err := t.Execute(w, response); err != nil {
log.Printf("Failed to execute template: %v", err)
}
}
和模板:
{{range .}} {{$form := .Form}}
<h1 class="blocks-header inlined">{{.Title}}</h1>
{{range .Content}}
<p>{{.Something}}</p>
{{template $form .}}
{{end}} {{end}}
$form
变量单独使用时<p>{{$form}}</p>
呈现为字符串,但是当用作模板名称时出现错误:unexpected "$form" in template clause
如何以template子句可以理解的方式传递模板名称?