从GO模板中获取原始源代码。

huangapple go评论92阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年11月2日 16:52:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/69807596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定