Datsik
Datsik

Reputation: 14824

How can I add FuncMaps to already parsed templates in golang

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.

Upvotes: 2

Views: 1454

Answers (1)

Datsik
Datsik

Reputation: 14824

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

Upvotes: 3

Related Questions