Go templates
Source: Dev.to
What are Go templates?
Go templates are a way to create dynamic content in Go by mixing data with plain text or HTML files. They allow you to replace placeholders in a template with values supplied from Go code, making it easy to generate pages that depend on user input or database content.
A template is just a file that contains placeholders written using double curly braces {{ }}. For example, {{ .Name }} inserts the Name field from the data object passed to the template. The dot (.) refers to the root data object.
Defining the data structure
Typically you define a struct (or a map) that holds the data you want to display:
type PageData struct {
Title string
Message string
}
Template file example
Below is a simple HTML template that uses several features of Go templates, such as variable interpolation, conditionals, and loops:
{{ .Title }}
## {{ .Title }}
{{ .Message }}
{{ if .IsLogged }}
Welcome back, {{ .User }}!
{{ else }}
Please login to continue.
{{ end }}
## Your Tasks:
{{ range .Tasks }}
- {{ . }}
{{ else }}
- No tasks available.
{{ end }}
Using templates in Go code
The following Go program parses the template file above and executes it with a PageData instance:
package main
import (
"html/template"
"net/http"
)
type PageData struct {
Title string
Message string
IsLogged bool
User string
Tasks []string
}
func handler(w http.ResponseWriter, r *http.Request) {
data := PageData{
Title: "Go Templates Advanced Example",
Message: "Using conditions and loops in templates",
IsLogged: true,
User: "Ian",
Tasks: []string{
"Learn Go templates",
"Build a web app",
"Practice Go daily",
},
}
tmpl := template.Must(template.ParseFiles("index.html"))
tmpl.Execute(w, data)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
Summary
Go templates let you separate presentation (HTML or text) from business logic, reuse layouts with different data, and build dynamic web pages, reports, or any text‑based content efficiently. They support basic logic such as conditionals, loops, and built‑in functions (e.g., len), giving you flexibility while keeping your code clean and maintainable.