Gin: Template FuncMap

Created on 28 Feb 2015  路  8Comments  路  Source: gin-gonic/gin

I've tried to get a funcmap injected via HTMLTemplate(...) but with no luck using it. Does anyone have any samples?

Thank you

Most helpful comment

Hello,

I do this:

    // instead of
    // r.LoadHTMLGlob("view/*.tmpl")

    // I do this
    if tmpl, err := template.New("projectViews").Funcs(utils.TemplateHelpers).ParseGlob("view/*.tmpl"); err == nil {
        r.SetHTMLTemplate(tmpl)
    } else {
        panic(err)
    }

But would be nice if I could do this:

    r.LoadHTMLGlob("view/*.tmpl", funcMap)

All 8 comments

Here it is (not complete but you'll get the idea)

func parseTemplate(tmpl string) *template.Template {

    funcMap := template.FuncMap{
        "marshal": func(v string) template.JS {
            //  a, _ := json.Marshal(v)
            return template.JS(v)
        },
        "noescape": func(s string) template.HTML {
            return template.HTML(s)
        },
    }

    tmpl_list := []string{"templates/base.html", fmt.Sprintf("templates/%s.html", tmpl)}
    t := template.New("base.html").Funcs(funcMap).Delims("[[", "]]")
    parsed, err := t.ParseFiles(tmpl_list...)
    if err != nil {
        panic(err)
    }
    return parsed
}

The issue is this breaks the c.HTML system? You'd have to actually render the form yourself?

I feel like funcmaps are so typical that this should be just a function we can add in from the base engine without overriding anything.

@TrollWarlord sorry for delay, Gin's template system is a wrapper of html/template. If you need to access all the functions, I suggest to add as external import, and use it directly instead of through Gin. However, I'll look into opening an API for injecting FuncMap.

Hello,

I do this:

    // instead of
    // r.LoadHTMLGlob("view/*.tmpl")

    // I do this
    if tmpl, err := template.New("projectViews").Funcs(utils.TemplateHelpers).ParseGlob("view/*.tmpl"); err == nil {
        r.SetHTMLTemplate(tmpl)
    } else {
        panic(err)
    }

But would be nice if I could do this:

    r.LoadHTMLGlob("view/*.tmpl", funcMap)

I would :+1: for @gustavopaes suggestion, but LoadHTMLFiles accepts a range of strings, so you'd have to come up with some funky code to support both functions.

It would be easier if there was a separate function altogheter to add a funcmap, like @TrollWarlord suggested.

In any case, :+1: for this new feature. Funcmaps are a common need.

+1
Gustavopaes made an really attractive suggestion.

+1
Gustavopaes made an really attractive suggestion.

I just did this package. hope it's help.

https://github.com/michelloworld/ez-gin-template

Was this page helpful?
0 / 5 - 0 ratings

Related issues

xpbliss picture xpbliss  路  3Comments

iiinsomnia picture iiinsomnia  路  3Comments

ccaza picture ccaza  路  3Comments

mastrolinux picture mastrolinux  路  3Comments

frederikhors picture frederikhors  路  3Comments