How to Extract Action Lists from a Parsed Go Template?
Dec 16, 2024 pm 12:12 PMObtaining an Action List from a Parsed Template
Question:
How can I retrieve a list of template actions (such as those defined by {{ .blahblah }}) from a parsed template?
Foreword:
The Template.Tree field, as mentioned, should not be relied upon for input provision in template execution. It is crucial to define the template and its expected data beforehand.
Solution:
To inspect a parsed template, navigate its parse tree (template.Template.Tree). Nodes within this tree represent various elements, including template actions. Here, we focus on nodes of type parse.NodeAction (Actions Evaluated as Fields).
Code Example:
The following code traverses the parse tree recursively to identify nodes with the NodeAction type:
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 }
Usage:
Invoke the ListTemplFields function on a parsed template to retrieve a list of action tokens:
t := template.Must(template.New("cooltemplate"). Parse(`<h1>{{ .name }} {{ .age }}</h1>`)) fmt.Println(ListTemplFields(t))
Output:
The output for the provided template will be:
[{{.name}} {{.age}}]
The above is the detailed content of How to Extract Action Lists from a Parsed Go Template?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go language pack import: What is the difference between underscore and without underscore?

How to implement short-term information transfer between pages in the Beego framework?

How do I write mock objects and stubs for testing in Go?

How can I use tracing tools to understand the execution flow of my Go applications?

How to convert MySQL query result List into a custom structure slice in Go language?

How can I define custom type constraints for generics in Go?

How to write files in Go language conveniently?

How do I write benchmarks that accurately reflect real-world performance in Go?
