This question already has an answer here:
I render templates this way:
func renderTemplate(...........) {
rt := template.Must(template.ParseFiles(
fmt.Sprintf("%s/%s", templatesPath, baseLayoutPath),
fmt.Sprintf("%s/%s", templatesPath, tplName)))
err := rt.ExecuteTemplate(w, "base", nil)
//[................]
}
I want to register a custom function in it:
func myTest1(string s) string {
return "hello: " + s
}
func renderTemplate(...........) {
rt := template.Must(template.ParseFiles(
fmt.Sprintf("%s/%s", templatesPath, baseLayoutPath),
fmt.Sprintf("%s/%s", templatesPath, tplName))).Funcs(template.FuncMap{"test1": myTest1})
This doesn't work: "test1" not defined"
// html template:
{{range .items}}
{{.Field1 | test1}}
Why not and how to make it work?
</div>
Add the template functions before you parse the templates.
From the html/template docs for Funcs():
Funcs adds the elements of the argument map to the template's function map. It must be called before the template is parsed.
funcMap := template.FuncMap{"test1":myTest1}
rt := template.Must(template.New("name").Funcs(funcMap).ParseFiles(
fmt.Sprintf("%s/%s", templatesPath, baseLayoutPath),
fmt.Sprintf("%s/%s", templatesPath, tplName)))