I have a HTML template that I execute passing a map[string]string variable. The template uses the variable to create the HTML output that I send to clients.
In addition to producing the HTML, I would like to use the very same template to generate some values that are retured to the main program, so I can use the same file to put some logic externally.
As far as I know, it is not possible to modify the variable I pass to Execute (something like {{.output = "value"}}
).
So how could I get multiple output values from a template Execution?
You don't actually need to pass a funcmap, just pass the struct.
var tmpl = template.Must(template.New("test").Parse(`Before: {{.Data}}{{.Set "YY"}}, after: {{.Data}}`))
func main() {
c := &CustomData{"XX"}
tmpl.Execute(os.Stdout, c)
fmt.Println()
}
You can always pass a FuncMap
to the template, here's an extremely simple example:
const tmpl = `Before: {{.Data}}{{.Set "YY"}}, after: {{.Data}}`
type CustomData struct {
Data string
}
func (c *CustomData) Set(d string) string { // it has to return anything
c.Data = d
return ""
}
func main() {
c := &CustomData{"XX"}
funcMap := template.FuncMap{
"Set": c.Set,
}
t, _ := template.New("test").Funcs(funcMap).Parse(tmpl) // don't ignore errors in real code
t.Execute(os.Stdout, c)
fmt.Println()
}