I define some template function, such as unescaped:

func unescaped(x string) interface{} { return template.HTML(x) }

then I use it in my template.

If I use this:

.....
e.LoadHTMLGlob("views/*")
// template funcs
e.SetFuncMap(template.FuncMap{
    "unescaped": unescaped,
})

then, the template compile failed with function unescaped not defined;

If I use this:

.....
// template funcs
e.SetFuncMap(template.FuncMap{
    "unescaped": unescaped,
})
e.LoadHTMLGlob("views/*")

then, SetFuncMap will failed:

SetFuncMap failed: cannot convert.

because gin.Engine has not initialize the render

Comment From: jinfei

const ( DateFormat = "2006-01-02" DateTimeFormat = "2006-01-02 15:04" ) func (engine *Engine) LoadHTMLGlob(pattern string) { myFuncs := map[string]interface{}{ "raw": func(text string) template.HTML { return template.HTML(text) }, // Format a date according to the application's default date(time) format. "date": func(date time.Time) string { return date.Format(DateFormat) }, "datetime": func(date time.Time) string { return date.Format(DateTimeFormat) }, "even": func(a int) bool { return (a % 2) == 0 }, "SubString": func(str string, begin, length int) (substr string) { // 将字符串的转换成[]rune rs := []rune(str) lth := len(rs)

        // 简单的越界判断
        if begin < 0 {
            begin = 0
        }
        if begin >= lth {
            begin = lth
        }
        end := begin + length
        if end > lth {
            end = lth
        }

        // 返回子串
        return string(rs[begin:end])
    },
}
if IsDebugging() {
    debugPrintLoadTemplate(template.Must(template.New("").Funcs(myFuncs).ParseGlob(pattern)))
    engine.HTMLRender = render.HTMLDebug{Glob: pattern}
} else {
    templ := template.Must(template.New("").Funcs(myFuncs).ParseGlob(pattern))
    engine.SetHTMLTemplate(templ)
}
// if IsDebugging() {
//  debugPrintLoadTemplate(template.Must(template.ParseGlob(pattern)))
//  engine.HTMLRender = render.HTMLDebug{Glob: pattern}
// } else {
//  templ := template.Must(template.ParseGlob(pattern))
//  engine.SetHTMLTemplate(templ)
// }

}

You can refer to my code

Comment From: appleboy

V1.2 support SetFuncMap func.

https://github.com/gin-gonic/gin/blob/v1.2/gin_test.go#L48-L70

or https://github.com/gin-gonic/gin#custom-template-funcs

Comment From: adamlamar

Reading the code, SetFuncMap must come before LoadHTMLGlob or LoadHTMLFiles