The problem you have is that "home"
and .Context
will be the 3:rd and 4:th argument of printf
and not the arguments of addClassIfActive
. The return value of addClassIfActive
becomes the 2:nd argument for printf
.
But the solution is simple: you don't have to use printf
to print.
If your function just returns a string, you can simply print it by writing:
{{addClassIfActive "home" .Context}}
Full working example:
package main
import (
"html/template"
"os"
)
type Context struct {
Active bool
}
var templateFuncs = template.FuncMap{
"addClassIfActive": func(tab string, ctx *Context) string {
if ctx.Active {
return tab + " content"
}
// Return nothing
return ""
},
}
var htmlTemplate = `{{addClassIfActive "home" .Context}}`
func main() {
data := map[string]interface{}{
"Context": &Context{true}, // Set to false will prevent addClassIfActive to print
}
// We create the template and register out template function
t := template.New("t").Funcs(templateFuncs)
t, err := t.Parse(htmlTemplate)
if err != nil {
panic(err)
}
err = t.Execute(os.Stdout, data)
if err != nil {
panic(err)
}
}
Output:
home content
Playground