Given a go html template object, how can I retrieve the original source definition?
I don’t see any functions in the docs, but there must be a way to do this.
CodePudding user response:
The template.Template
type has a Template.Tree
exported field which contains (models) the parsed template.
Please note that even though this field is exported, it is not exported for you to use it, but quoting from the doc:
The *parse.Tree field is exported only for use by html/template and should be treated as unexported by all other clients.
Putting this aside, having the parse tree, it's possible to reconstruct the source from which it was built. parse.Tree
has a Root
field which has a String()
method, which builds the source text from the tree.
For example:
src := `Hi {{.Name}}. You are {{.Age}} years old.`
t := template.Must(template.New("").Parse(src))
fmt.Println(t.Tree.Root.String())
This will output (try it on the Go Playground):
Hi {{.Name}}. You are {{.Age}} years old.
As noted earlier: Template.Tree
is not part of the public API. You may use it, but it's not guaranteed it'll remain exported and it'll work the same in future versions. What you should do is keep the source which you parse, and not rely on Template.Tree
.