我有我的模板,這些模板最初是在應用程序啟動時解析的(顯然是出于這樣的速度原因)var templates = template.New("template")filepath.Walk("views", func(path string, info os.FileInfo, err error) error { if strings.HasSuffix(path, ".html") { templates.ParseFiles(path) } return nil})log.Println("Templates Parsed")然后我將我的 funcmaps 添加到它們自己的函數中(因為我需要請求對象,所以我可以像這樣獲取它們的會話數據)func View(w http.ResponseWriter, r *http.Request, tmplN string, data interface{}) { tmpl := templates.Funcs(template.FuncMap{ "username": func() string { session := Sesh(r) username := "" if session.Values["username"] != nil { username = session.Values["username"].(string) } return username }, "authenticated": func() bool { session := Sesh(r) authenticated := false if session.Values["authenticated"] != nil { authenticated = session.Values["authenticated"].(bool) } return authenticated }, }) err := tmpl.ExecuteTemplate(w, tmplN, data) if err != nil { log.Println("Error " + err.Error()) }}但似乎如果我Funcs在解析模板之前不調用它就不起作用,例如,如果我嘗試在我的register模板中使用,如下所示:{{ define "register" }} {{ template "_header" .}} {{ if authenticated }} // Call FuncMap function {{ end }}<br/><br/><br/><div class="row align-center"> <div class="large-4 columns text-center"> <div id="RegistrationFormComponent"></div> </div></div> {{ template "_footer" .}}{{ end }}我收到“注冊”不存在的錯誤,因為該函數authenticated在嘗試解析它時拋出錯誤。任何有關如何使其按預期工作的信息都將非常感謝。
1 回答

不負相思意
TA貢獻1777條經驗 獲得超10個贊
所以我想通了,但我將這個答案留在這里,因為它似乎在任何地方都沒有答案,基本上我可以定義一個冗余FuncMap來模擬我將在會話中使用的那個,然后將它們返回空白,然后我可以用FuncMap我的view函數(在問題帖子中可見)覆蓋它們,如下所示:
var templates = template.New("template").Funcs(template.FuncMap{
"authenticated": func() bool {
log.Println("Was I called?")
return false
},
"username": func() string {
return ""
},
})
- 1 回答
- 0 關注
- 258 瀏覽
添加回答
舉報
0/150
提交
取消