Skip to content

proposal: text/template: add reverse Execute method (parse text into struct) #52473

@ianling

Description

@ianling

text/template currently allows a developer to pass in a struct to print the struct's fields in an arbitrary format. Here is the example from the pkg.go.dev page that prints "17 items are made of wool"

type Inventory struct {
	Material string
	Count    uint
}
sweaters := Inventory{"wool", 17}
tmpl, _ := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
_ = tmpl.Execute(os.Stdout, sweaters)

I propose that a method be added that allows the reverse of this operation: parsing data from a body of text into the given struct, similar to unmarshalling JSON.

The following example parses the Count and Material fields out of the textToParse string and stores the values in sweaters. It would then print the data to stdout using the same template that was used to parse the data.

type Inventory struct {
	Material string
	Count    uint
}
tmpl, _ := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")

var sweaters Inventory
textToParse := "17 items are made of wool"
_ = tmpl.ReverseExecute(textToParse, &sweaters) // this is the new thing being proposed
_ = tmpl.Execute(os.Stdout, sweaters)

(ReverseExecute is a bad name for this method and should be changed.)

Compared to alternative approaches, such as parsing values out of a string using regex, this has the benefit of using one thing (a template) to perform both the parsing and writing operations. Passing a struct into this method also removes much of the manual work and wheel re-invention a developer would need to go through to parse arbitrary text into a struct, with regards to type checks and casting.

Potential issues for discussion:

  • How to handle excess whitespace?
    • For example, what if the template is only expecting one newline character between values, but text is given with two newlines? Should there be an option to ignore extra whitespace?
  • Should the template be "fuzzy", or allow lines to appear out of order?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions