template.New, Parse, Must, and Execute
func New(name string) *Template
func Must(t *Template, err error) *Template
func (t *Template) Parse(text string) (*Template, error)
func (t *Template) Execute(wr io.Writer, data any) errorParse a trusted template, then Execute it with data. text/template does not escape HTML.
| Parameter | Description |
|---|---|
name, text | New names the template. Parse reads the template body, which must be trusted. |
wr, data | Execute writes the result to wr using values from data. Maps and structs are common data types. |
Returns: Must returns the template or panics. Execute returns a non-nil error if execution or writing fails.
Errors
error— Parse returns a parse error for invalid syntax. This successful example has no execution error.
package main
import (
"bytes"
"fmt"
"text/template"
)
func main() {
t := template.Must(template.New("t").Parse("{{.Name}} has {{.Count}} items."))
var ok bytes.Buffer
if err := t.Execute(&ok, map[string]any{"Name": "Ada", "Count": 3}); err != nil {
fmt.Println(err)
return
}
fmt.Printf("%q\n", ok.String())
}Expected output
"Ada has 3 items."
Related: html/template, Official text/template