Go by Example

Text Templates

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

A template is text with marked places where data will be inserted. Go's text/template package fills those places to produce plain text. html/template does the same for web pages and escapes special HTML characters in the inserted data.

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 web pages and text/template for plain text such as a configuration file. Parse a template once and reuse it. Check errors from Execute. Do not mark user-provided text as trusted HTML, because that disables the automatic escaping that helps prevent unsafe page content.

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