2 回答
TA貢獻1830條經驗 獲得超9個贊
你不需要調用 ParseFiles 和 Must,你可以調用一個或另一個
func RenderTemplate(w http.ResponseWriter, data interface{}, tmpl... string) {
cwd, _ := os.Getwd()
for _,file:=range tmpl{
file=filepath.Join(cwd,"./view/"+file+".html")
}
t, err := template.ParseFiles(tmpl...)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = t.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
我相信上面的 func 應該做你想做的......
TA貢獻1811條經驗 獲得超5個贊
template.Must() 有這個簽名:
func Must(t *Template, err error) *Template
的參數Must()“巧合”與返回值相同ParseFiles(),ParseGlob()因此Must()如果錯誤非零,您可以在內部使用這些函數并產生恐慌的效果。所以你可以說
t := template.Must(template.ParseFiles(....))
并且不關心錯誤檢查。這只是一個方便的函數,類似于Must()整個標準庫中的所有其他函數,例如regexp.MustCompile().
的實現Must()很簡單:
func Must(t *Template, err error) *Template {
if err != nil {
panic(err)
}
return t
}
見https://golang.org/src/text/template/helper.go?s=576:619#L11
- 2 回答
- 0 關注
- 209 瀏覽
添加回答
舉報
