Home >Backend Development >Golang >How to Extract Action Lists from a Parsed Go Template?

How to Extract Action Lists from a Parsed Go Template?

Linda Hamilton
Linda HamiltonOriginal
2024-12-16 12:12:11587browse

How to Extract Action Lists from a Parsed Go Template?

Obtaining 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn