Render text templates
Render text templates
The text/template package combines trusted template source with data to produce plain text. Parse checks syntax and Execute writes the rendered result to an io.Writer. Inside {{...}}, dot is the current data value. Templates can read exported fields and execute registered functions; do not treat untrusted template source as harmless data.
package main
import ( "bytes" "fmt" "text/template")
func check(e error) { if e != nil { panic(e) }}
func main() { t, e := template.New("notice").Parse(`Hello {{.Name}}!`) check(e) var b bytes.Buffer check(t.Execute(&b, struct{ Name string }{"Sara"})) fmt.Println(b.String())}New names the template; Parse returns the template and a possible error. Execute receives the output destination and the data separately. Name must be accessible from the supplied struct. Use a buffer when you want to publish output only after execution succeeds. Must can simplify trusted fixed initialization but panics on errors.
Expected output:
Hello Sara!Control flow and pipelines
package main
import ( "bytes" "fmt" "strings" "text/template")
func check(e error) { if e != nil { panic(e) }}
func main() { t, e := template.New("list").Funcs(template.FuncMap{"upper": strings.ToUpper}).Parse(`{{range .}}{{. | upper}} {{else}}empty{{end}}`) check(e) for _, items := range [][]string{{"tea", "rice"}, nil} { var b bytes.Buffer check(t.Execute(&b, items)) fmt.Printf("%q\n", b.String()) }}Register functions before parsing names that use them. range changes dot to each element, and else handles an empty slice. A pipeline passes its result as the final argument to the next command. A template can fail during execution even if parsing succeeded; for missing map keys consider Option("missingkey=error"). Execution may already have written partial output, so check errors before using the buffer.
Expected output:
"TEA RICE ""empty"Try it locally
Render Items: {{len .}} with a slice of three strings and print the result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Text processing 05: Render text templates
Check the lesson objective before moving on.
What is dot inside a range over a slice?
Why render into a buffer first?