英文:
Get raw source from GO template
问题
给定一个go html模板对象,我如何获取原始的源代码定义?
我在文档中没有看到任何函数,但一定有一种方法可以做到这一点。
英文:
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.
答案1
得分: 1
template.Template
类型有一个 Template.Tree
导出字段,其中包含(模型)解析的模板。
请注意,尽管该字段是导出的,但它不是为了供您使用,但引用文档中的内容:
> *parse.Tree 字段仅供 html/template 使用,并且应该被所有其他客户端视为未导出。
撇开这一点,有了解析树,可以从中重建构建它的源代码。parse.Tree
有一个 Root
字段,它具有 String()
方法,用于从树中构建源文本。
例如:
src := `Hi {{.Name}}. You are {{.Age}} years old.`
t := template.Must(template.New("").Parse(src))
fmt.Println(t.Tree.Root.String())
这将输出(在 Go Playground 上尝试):
Hi {{.Name}}. You are {{.Age}} years old.
如前所述:Template.Tree
不是公共 API 的一部分。您可以使用它,但不能保证它将保持导出状态,并且在将来的版本中它将起作用。您应该保留解析的源代码,而不依赖于 Template.Tree
。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论