drgmszo076956 2015-12-30 05:55
浏览 32
已采纳

如何在Golang中将FuncMaps添加到已解析的模板中

I have my templates which are initially parsed on the app launch (obviously for speed reasons like this)

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")

Then I have my funcmaps which get added in their own function (because I need the request object so I can get their session data like so)

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())
    }
}

But it seems like if I don't put the Funcs call before the parsing of the templates it doesn't work, e.g. if I try to use in my register template like so:

{{ 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 }}

I get an error that "register" does not exist because the function authenticated throws an error when it's trying to parse it. Any information on how I can get this to work as intended would be great thanks.

  • 写回答

1条回答 默认 最新

  • doutingyou2198 2015-12-30 06:55
    关注

    So I figured it out, but I'll leave this answer here as it seems to not be answered anywhere, basically I can define a redundant FuncMap that mimics the one I will be using with the sessions, and just return them blank, I can then overwrite them with the FuncMap from my view function (visible in the question post) like this:

    var templates = template.New("template").Funcs(template.FuncMap{
        "authenticated": func() bool {
            log.Println("Was I called?")
            return false
        },
        "username": func() string {
            return ""
        },
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line