Retrieving a List of Template Actions from a Parsed Template
How can you extract the templates defined in a template as a slice of strings? Consider a template like:
<h1>{{ .name }} {{ .age }}</h1>
You wish to obtain []string{"name", "age"}.
Inspecting the Parsed Template Tree
The parsed template is represented by a template.Tree containing details about the template structure. Each node of this tree has a Node.Type() method that provides information about its type. Relevant types include:
Iterating the Tree
To identify actions within the template, you can iterate through the tree and explore the nodes. The following sample function demonstrates this process:
import ( "text/template/parse" ) 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 }
Example Usage
To determine the fields required for the template:
t := template.Must(template.New("cooltemplate"). Parse(`<h1>{{ .name }} {{ .age }}</h1>`)) fmt.Println(ListTemplFields(t))
The output will be:
[{{.name}} {{.age}}]
Note: This demonstration is not comprehensive and may not handle all cases. However, it illustrates the concept of extracting template actions by introspecting the parsed template tree.
The above is the detailed content of How to Extract Template Field Names from a Parsed Go Template?. For more information, please follow other related articles on the PHP Chinese website!