Get raw source from GO template

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.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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))

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.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x