Home > Backend Development > Golang > How to Extract Template Field Names from a Parsed Go Template?

How to Extract Template Field Names from a Parsed Go Template?

Barbara Streisand
Release: 2024-12-18 21:43:18
Original
937 people have browsed it

How to Extract Template Field Names from a Parsed Go Template?

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

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:

  • NodeAction: Non-control actions such as field evaluations
  • NodeField: Field or method names

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

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

The output will be:

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

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!

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