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
Release: 2024-12-16 12:12:11
Original
581 people have browsed it

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
}
Copy after login

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))
Copy after login

Output:

The output for the provided template will be:

[{{.name}} {{.age}}]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template