Skip to content

Go Text Templates

Templates are a way to generate dynamic text (like HTML, emails, or reports) by combining a static string with dynamic data.

Basic Example

Go templates use double curly braces {{ }} to mark dynamic parts. Inside the template, {{.}} refers to the data passed in.

package main

import (
    "os"
    "text/template"
)

func main() {
    // 1. Define a template string
    tmpl := "Hello {{.Name}}, welcome to {{.City}}!\n"

    // 2. Parse the template
    t, _ := template.New("test").Parse(tmpl)

    // 3. Create data (a struct or a map)
    data := struct {
        Name, City string
    }{
        Name: "Alice",
        City: "NY",
    }

    // 4. Executing the template sends results to os.Stdout
    t.Execute(os.Stdout, data)
}

Control Structures

Templates support loops and conditions:

  • Conditions: {{if .Condition}} ... {{else}} ... {{end}}
  • Loops: {{range .Slice}} ... {{.}} ... {{end}}
tmpl := `
{{if .Admin}}
  Admin Console
{{else}}
  User Dashboard
{{end}}

Friends:
{{range .Friends}}
  - {{.}}
{{end}}
`

Accessing Fields

If you pass a struct to a template, you can access its fields using a dot: {{.FieldName}}.

1
2
3
4
5
6
7
type User struct {
    ID   int
    Name string
}

// In template:
// User ID: {{.ID}}, Name: {{.Name}}

Why use Templates?

  1. Separation of Concerns: Keep your text/HTML separate from your Go code.
  2. Reusable Layouts: Define a "base" layout and swap the content inside.
  3. Security: If you use html/template (instead of text/template), Go will automatically escape special characters to prevent XSS attacks. factory methods.