Golang Gin html/template custom function not working in template

78 Views Asked by At

I am trying to add a custom function that I can use in the html template. Code as follows: returns error on undefined function

`func main() {

router := gin.Default()
router.HTMLRender = LoadTemplates("./app")
hrmGroup := router.Group("/hrm")
hrmGroup.Use(controllers.HRMLoginCheck())
{
    hrmGroup.GET("/", controllers.Index)
    hrmGroup.GET("/leave-management/leave-compose", 
controllers.LeaveComposeLeaveManagement)
}
router.Run(app.PORT)
}

Load the template file using the following function. I am using Multitemplate.Renderer

func LoadTemplates(templatesDir string) multitemplate.Renderer {
r := multitemplate.NewRenderer()


/// hrm load templates

hrmLayouts, err := filepath.Glob(templatesDir + "/hrm_views/layouts/base.html")
if err != nil {
    panic(err.Error())
}

hrm_pages, err := filepath.Glob(templatesDir + "/hrm_views/*.html")
if err != nil {
    panic(err.Error())
}

for _, page := range hrm_pages {
    layoutCopy := make([]string, len(hrmLayouts))
    copy(layoutCopy, hrmLayouts)
    files := append(layoutCopy, page)
    r.AddFromFiles(filepath.Base(page), files...)
}

hrm_pages, err = filepath.Glob(templatesDir + "/hrm_views/*/*.html")
if err != nil {
    panic(err.Error())
}

for _, page := range hrm_pages {
    layoutCopy := make([]string, len(hrmLayouts))
    copy(layoutCopy, hrmLayouts)
    files := append(layoutCopy, page)
    r.AddFromFiles(filepath.Base(page), files...)

    fmt.Println(page)
    fmt.Println(filepath.Base(page))
    
    r.AddFromFilesFuncs(filepath.Base(page), template.FuncMap{
        "my_func": func() string {
            return "xyz"
        },
    }, files...)

}

return r
}

// in template file

{{my_func}}

`

panic: template: leave-compose.html:272: function "my_func" not defined

0

There are 0 best solutions below