Go by Example

Text Templates

Render data with Go templates and use HTML escaping for browser output.

Go templates combine a template string with data to produce text. text/template is for plain text; html/template has the same API and escapes values for HTML output.

Template actions use double braces. The dot refers to the data passed to Execute. html/template escapes markup in the Name value.

package main
 
import (
    "html/template"
    "os"
)
 
func main() {
    tmpl := template.Must(template.New("greeting").Parse(
        "<p>Hello, {{.Name}}</p>",
    ))
    data := struct{ Name string }{"<script>"}
    if err := tmpl.Execute(os.Stdout, data); err != nil {
        panic(err)
    }
}

In production

Use html/template for browser output and text/template for plain text such as configuration files. Parse templates once and reuse them. Always handle Execute errors, and do not mark untrusted input as template.HTML because that bypasses escaping.

Enjoyed this? Get more software craft delivered to your inbox.