Jac*_*unt 3 templates go go-templates
所以我想以某种方式将我{{ .blahblah }}
在模板中定义的所有操作作为字符串切片。
例如,如果我有这个模板:
<h1>{{ .name }} {{ .age }}</h1>
Run Code Online (Sandbox Code Playgroud)
我希望能够得到[]string{"name", "age"}
。假设模板具有方法func (t *Template) Fields() []string
:
t := template.New("cooltemplate").Parse(`<h1>{{ .name }} {{ .age }}</h1>`)
if t.Fields() == []string{"name", "age"} {
fmt.Println("Yay, now I know what fields I can pass in!")
// Now lets pass in the name field that we just discovered.
_ = t.Execute(os.Stdout, map[string]string{"name": "Jack", "age":"120"})
}
Run Code Online (Sandbox Code Playgroud)
有没有办法检查这样的解析模板?
谢谢!
前言:正如 Voker 所建议的那样,该Template.Tree
字段“仅导出供 html/模板使用,并且应被所有其他客户端视为未导出。”
你不应该依赖这样的东西来为模板执行提供输入。您必须知道要执行的模板及其预期的数据。你不应该在运行时“探索”它来为它提供参数。
您从解析模板中获得的价值是template.Template
(text/template
或者html/template
,它们具有相同的 API)。此模板将模板表示为类型树parse.Tree
。文本模板包含的所有内容都存储在此树中的节点中,包括静态文本、动作等。
话虽如此,您可以遍历此树并查找标识访问字段或调用函数的此类操作的节点。节点的类型parse.Node
具有Node.Type()
返回其类型的方法。可能的类型被定义为parse
包中的常量,在parse.NodeType
类型旁边,例如
const (
NodeText NodeType = iota // Plain text.
NodeAction // A non-control action such as a field evaluation.
NodeBool // A boolean constant.
NodeChain // A sequence of field accesses.
NodeCommand // An element of a pipeline.
NodeDot // The cursor, dot.
NodeField // A field or method name.
NodeIdentifier // An identifier; always a function name.
NodeIf // An if action.
NodeList // A list of Nodes.
NodeNil // An untyped nil constant.
NodeNumber // A numerical constant.
NodePipe // A pipeline of commands.
NodeRange // A range action.
NodeString // A string constant.
NodeTemplate // A template invocation action.
NodeVariable // A $ variable.
NodeWith // A with action.
)
Run Code Online (Sandbox Code Playgroud)
因此,这里有一个示例程序,它递归地遍历模板树,并查找NodeAction
类型为“非控制操作,例如字段评估”的节点。
这个解决方案只是一个演示,一个概念证明,它不能处理所有情况。
func ListTemplFields(t *template.Template) []string {
return listNodeFields(t.Tree.Root, nil)
}
func listNodeFields(node parse.Node, res []string) []string {
if node.Type() == parse.NodeAction {
res = append(res, node.String())
}
if ln, ok := node.(*parse.ListNode); ok {
for _, n := range ln.Nodes {
res = listNodeFields(n, res)
}
}
return res
}
Run Code Online (Sandbox Code Playgroud)
使用示例:
t := template.Must(template.New("cooltemplate").
Parse(`<h1>{{ .name }} {{ .age }}</h1>`))
fmt.Println(ListTemplFields(t))
Run Code Online (Sandbox Code Playgroud)
输出(在Go Playground上试试):
[{{.name}} {{.age}}]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2162 次 |
最近记录: |