亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將 FuncMaps 添加到 golang 中已解析的模板中

如何將 FuncMaps 添加到 golang 中已解析的模板中

Go
呼如林 2021-12-06 14:57:42
我有我的模板,這些模板最初是在應用程序啟動時解析的(顯然是出于這樣的速度原因)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 ""

    },

})


查看完整回答
反對 回復 2021-12-06
  • 1 回答
  • 0 關注
  • 258 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號