html/template.Execute versus text/template.Execute
func New(name string) *Template
func (t *Template) Parse(text string) (*Template, error)
func (t *Template) Execute(wr io.Writer, data any) errorhtml/template escapes untrusted data for HTML context. text/template does not. Both programs print quoted strings, not a live page.
| Parameter | Description |
|---|---|
name, text | New allocates a template. Parse reads the template source, which must be trusted. |
wr, data | Execute writes the result to wr. data is treated as untrusted content in html/template. |
Returns: Parse returns the template and an error. Execute returns an error if execution or writing fails.
Errors
error— A parse or execution error is returned to the caller. This example checks both and then prints the buffers.
- The two outputs are printed with %q so the escaped and raw forms stay visible as data.
package main
import (
"bytes"
"fmt"
htmltemplate "html/template"
texttemplate "text/template"
)
func main() {
data := "<b>ok</b>"
textT, err := texttemplate.New("t").Parse("Hello, {{.}}!")
if err != nil {
fmt.Println(err)
return
}
htmlT, err := htmltemplate.New("t").Parse("Hello, {{.}}!")
if err != nil {
fmt.Println(err)
return
}
var textOut, htmlOut bytes.Buffer
if err := textT.Execute(&textOut, data); err != nil {
fmt.Println("text", err)
}
if err := htmlT.Execute(&htmlOut, data); err != nil {
fmt.Println("html", err)
}
fmt.Printf("%q\n", textOut.String())
fmt.Printf("%q\n", htmlOut.String())
}Expected output
"Hello, <b>ok</b>!"
"Hello, <b>ok</b>!"
Related: text/template, html.EscapeString