When a large piece of mostly static text needs a few dynamic values, a template is often clearer than assembling strings with fmt.Sprintf or strings.Builder. Go’s text/template package parses text containing actions such as {{ . }} and executes it against supplied data to produce output. section 11.1.2 section 11.6
A small template follows a direct workflow:
- Keep the template in a separate file, optionally load it with //go:embed, then call template.New("name").Parse(contents). Handle parse errors before producing output. section 11.1.2 section 11.6
- Call Execute(writer, data) and handle its error. Within the template, {{ . }} prints the current value; {{ .Field }} reads an exposed field. section 11.1.2 section 11.2.2
- Use {{ range . }} … {{ end }} to repeat output for a collection. Inside the range, dot becomes the current item; {{- and -}} can trim unwanted whitespace. section 11.2.2
Generate a stylesheet
A styles.css template can set background-color: {{.Background}} and color: {{.Foreground}}. An HTTP handler parses the embedded file with text/template, sets Content-Type to text/css, then executes it with Background and Foreground values. The result is CSS assembled without concatenating the stylesheet in Go code. section 11.5.3
Listing 11.48 styles.go: Applies the CSS
import (
_ "embed"
"text/template" #1
...
)
//go:embed templates/styles.css
var stylesPage string
func (s *Server) styles(w http.ResponseWriter, r *http.Request) {
tpl, err := template.New("styles").Parse(stylesPage)
if err != nil {...}
w.Header().Add("Content-Type", "text/css") #2
err = tpl.Execute(w, map[string]interface{}{
"Background":"DarkSlateGray",
"Foreground":"LightGray"}) #3
if err != nil {...}
}
The handler shows the package import, parse-and-execute calls, data map, and CSS response header together. section 11.5.3
Choose html/template instead when rendering HTML: it shares the template interface but escapes values to protect the page from HTML injection. text/template does not provide that protection, so consider whether values are safe for the format being generated. Templates also depend on exposed Go field names; renaming or hiding a field breaks its use in the template. Although methods can be called under return-value constraints, keeping complex calls out of templates makes them easier to read. section 11.1.2 section 11.2.2

