The idea is to define a variable for a go template which is also a template using variables (a nested template) like this:
package main
import (
"os"
"text/template"
)
type Todo struct {
Name string
Description string
Subtemplate string
}
func main() {
td := Todo{
Name: "Test name",
Description: "Test description",
Subtemplate: "Subtemplate {{.Name}}",
}
t, err := template.New("todos").Parse("{{.Subtemplate}} You have a task named \"{{ .Name}}\" with description: \"{{ .Description}}\"")
if err != nil {
panic(err)
}
err = t.Execute(os.Stdout, td)
if err != nil {
panic(err)
}
}
The result of the code above is however:
Subtemplate {{.Name}} You have a task named "Test name" with description: "Test description"
means the variable .Name
in the subtemplate is not resolved (probably by design not possible, would require some kind of a recursive call). Is there any/other way to achieve this effect?
It should work for the template functions defined using template.FuncMap
too. Thanx.