はじめに:Vokerが示唆しているように、Template.Tree
フィールドは「」であり、「html/templateでのみ使用するためにエクスポートされており、他のすべてのクライアントからは認識されないように扱われるべきです。
テンプレート実行の入力を提供するには、このようなことに頼るべきではありません。必要なデータとともに実行したいテンプレートを知っている必要があります。実行時に引数を提供するためにそれを "探索"するべきではありません。
テンプレートを解析から抜け出す値が(text/template
またはhtml/template
のいずれか、彼らは同じAPIを持つ)template.Template
です。このテンプレートは、テンプレートをタイプparse.Tree
のツリーとして表します。テキストテンプレートに含まれるすべてのものが、静的テキスト、アクションなどを含むノード内のこのツリーに格納されます。
このことから、このツリーを歩いて、フィールドまたはコール関数にアクセスするアクションを識別するノードを探すことができます。ノードはタイプがNode.Type()
であるタイプparse.Node
です。可能なタイプは、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}}]
テンプレートは、原料のこの種(FieldNode)を公開parse.Treeが含まれています。 docs: "* parse.Treeフィールドは、html/templateでのみ使用するためにエクスポートされ、他のすべてのクライアントからは認識されないように扱われなければなりません。 So:それをしないでください。あなたがそのアドバイスに従わなければ:幸運。 – Volker