3 回答

TA贡献1790条经验 获得超9个赞
前言:正如 Voker 所建议的,该Template.Tree字段“仅导出供 html/template 使用,应被所有其他客户端视为未导出”。
您不应该依赖这样的东西来为模板执行提供输入。您必须知道要执行的模板及其预期的数据。你不应该在运行时“探索”它来为它提供参数。
您从解析模板中获得的价值是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.
)
因此,这里有一个示例程序,它递归地遍历模板树,并查找具有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
}
使用它的示例:
t := template.Must(template.New("cooltemplate").
Parse(`<h1>{{ .name }} {{ .age }}</h1>`))
fmt.Println(ListTemplFields(t))
输出(在Go Playground上试试):
[{{.name}} {{.age}}]

TA贡献2012条经验 获得超12个赞
回答进行了一个小优化,也许会有所帮助:)
func listNodeFieldsV2(node parse.Node) []string {
var res []string
if node.Type() == parse.NodeAction {
res = append(res, node.String())
}
if ln, ok := node.(*parse.ListNode); ok {
for _, n := range ln.Nodes {
res = append(res, listNodeFieldsV2(n)...)
}
}
return res
}

TA贡献1834条经验 获得超8个赞
我碰巧需要大致相同的代码。在我的用例中,我们允许用户在一侧创建模板,并输入map[string]string用于以不同形式呈现的变量。
这是我到目前为止提出的代码(受 icza 的回答启发):
// Extract the template vars required from *simple* templates.
// Only works for top level, plain variables. Returns all problematic parse.Node as errors.
func RequiredTemplateVars(t *template.Template) ([]string, []error) {
var res []string
var errors []error
var ln *parse.ListNode
ln = t.Tree.Root
Node:
for _, n := range ln.Nodes {
if nn, ok := n.(*parse.ActionNode); ok {
p := nn.Pipe
if len(p.Decl) > 0 {
errors = append(errors, fmt.Errorf("Node %v not supported", n))
continue Node
}
for _, c := range p.Cmds {
if len(c.Args) != 1 {
errors = append(errors, fmt.Errorf("Node %v not supported", n))
continue Node
}
if a, ok := c.Args[0].(*parse.FieldNode); ok {
if len(a.Ident) != 1 {
errors = append(errors, fmt.Errorf("Node %v not supported", n))
continue Node
}
res = append(res, a.Ident[0])
} else {
errors = append(errors, fmt.Errorf("Node %v not supported", n))
continue Node
}
}
} else {
if _, ok := n.(*parse.TextNode); !ok {
errors = append(errors, fmt.Errorf("Node %v not supported", n))
continue Node
}
}
}
return res, errors
}
https://play.golang.org/p/nH95B45jUmI
- 3 回答
- 0 关注
- 127 浏览
添加回答
举报