我正在尝试html/template在 Go 中使用嵌入模板。我非常喜欢无逻辑的模板设计,并且我相信它能够按预期安全地逃避事情(有时其他模板库会出错)。
但是,我在尝试实现一个小助手以根据“最终”模板名称在我的 HTTP 处理程序中呈现我的模板时遇到了一些问题。我的 base.tmpl 在我的所有页面中实际上都是“标准的”,如果不是,我可以{{ template checkoutJS }}在 base.tmpl 中设置并通过设置添加一些每页 JS {{ define checkoutJS }}https://path.to/extra.js {{ end }}。
我希望能够renderTemplate(w, "template_name.tmpl", data)在我的 HTTP 处理程序中说,datamap[string]interface{} 包含字符串或结构,其中包含我希望填写的任何内容。
这是到目前为止的代码:
基础.tmpl
{{ define "base" }}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{ template "title" . }}</title>
</head>
<body>
<div id="sidebar">
...
</div>
{{ template "content" }}
<div id="footer">
...
</div>
</body>
</html>
create_listing.tmpl
{{ define "title" }}Create a New Listing{{ end }}
{{ define "content" }}
<form>
  ...
</form>
{{ end }}
login_form.tmpl
{{ define "title" }}Login{{ end }}
{{ define "content" }}
<form>
  ...
</form>
{{ end }}
main.go
package main
import (
  "fmt"
    "github.com/gorilla/mux"
    "html/template"
    "log"
    "net/http"
)
// Template handling shortcuts
var t = template.New("base")
func renderTemplate(w http.ResponseWriter, tmpl string, data map[string]interface{}) {
    err := t.ExecuteTemplate(w, tmpl, data)
  // Things will be more elegant than this: just a placeholder for now!
    if err != nil {
        http.Error(w, "error 500:"+" "+err.Error(), http.StatusInternalServerError)
    }
}
func monitorLoginForm(w http.ResponseWriter, r *http.Request) {
    // Capture forms, etc.
    renderTemplate(w, "login_form.tmpl", nil)
}
func createListingForm(w http.ResponseWriter, r *http.Request) {
    // Grab session, re-populate form if need be, generate CSRF token, etc
    renderTemplate(w, "create_listing.tmpl", nil)
}
func main() {
    r := mux.NewRouter()
    r.HandleFunc("/monitor/login", monitorLoginForm)
    http.Handle("/", r)
    log.Fatal(http.ListenAndServe(":8000", nil))
}
func init() {
    fmt.Println("Starting up.")
    _, err := t.ParseGlob("templates/*.tmpl")
    if err != nil {
        log.Fatal("Error loading templates:" + err.Error())
    }
}
这编译,但我从我的处理程序返回一个空响应。请注意,我没有第二个处理程序的路线:该代码只是为了显示我想如何renderTemplate()从处理程序调用。