【问题标题】:Get raw source from GO template从 GO 模板获取原始源代码
【发布时间】:2021-12-16 19:32:27
【问题描述】:

给定一个 go html 模板对象,我如何检索原始源定义?

我在文档中没有看到任何函数,但一定有办法做到这一点。

【问题讨论】:

  • 你想要什么?您想从客户端获取模板源吗?请澄清您的问题。
  • 我想将 *Template 转回其源 html。我不想要编译后的 html。我想在运行 ExecuteTemplate 之前查看源 html,并在客户端对其进行编辑。

标签: html go templates


【解决方案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。

【讨论】:

    猜你喜欢
    • 2017-04-14
    • 1970-01-01
    • 2021-04-15
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多