Home >Backend Development >Golang >How to Extract a List of Actions from a Go Template?

How to Extract a List of Actions from a Go Template?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-17 04:16:25955browse

How to Extract a List of Actions from a Go Template?

How to Access Template "Actions" in Go

Templates provide a powerful way to render data into structured text. In some cases, it may be desirable to introspect a template to determine the list of actions it defines.

Template Structure

A parsed template is represented as a tree of nodes. Each node represents a specific construct within the template, such as text, actions, or control structures.

Identifying Actions

Actions are nodes that define how data should be retrieved or processed. They can be used to access fields or invoke functions in the data model. To identify action nodes in the tree, check for nodes of type parse.NodeAction.

Example Implementation

Here's an example function that recursively walks the template tree and collects all action nodes:

func ListTemplateActions(t *template.Template) []string {
    return listNodeActions(t.Tree.Root, nil)
}

func listNodeActions(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 = listNodeActions(n, res)
        }
    }

    return res
}

This function returns a slice of strings containing the textual representation of each action node.

Usage

To use this function, parse the template and then call ListTemplateActions. For example:

t := template.Must(template.New("test").
    Parse(`<p>{{ .name }} - {{ .age }}</p>`))
fmt.Println(ListTemplateActions(t))

Output:

[{{.name}} {{.age}}]

This demonstration shows how to identify and retrieve a list of actions defined in a parsed template, allowing you to determine the input it expects and dynamically construct the data model accordingly.

The above is the detailed content of How to Extract a List of Actions from a 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