Advanced Go Concepts
Estimated reading: 4 minutes 288 views

Go – Templates Explained with Syntax, Examples & Real Use Cases (2025 Guide)

Introduction – What Are Templates in Go?

Go’s text/template and html/template packages allow developers to generate dynamic text or HTML by embedding logic into templates. Templates are commonly used in web development, code generation, and email formatting, allowing you to separate presentation from logic.

In this section, you’ll learn:

  • How to define and execute text and HTML templates
  • Use variables, loops, conditionals, and custom functions in templates
  • Escape and sanitize output (especially in html/template)
  • Real-world use cases like email rendering and HTML generation

Basic Example – Text Template

package main

import (
    "os"
    "text/template"
)

func main() {
    tmpl := `Hello, {{.}}!`
    t := template.Must(template.New("greet").Parse(tmpl))
    t.Execute(os.Stdout, "Go Developer")
}

Output:

Hello, Go Developer!

{{.}} refers to the current data context passed during execution.


Using Structs as Template Data

type User struct {
    Name string
    Age  int
}

func main() {
    u := User{"Alice", 30}
    tmpl := `Name: {{.Name}}, Age: {{.Age}}`
    t := template.Must(template.New("user").Parse(tmpl))
    t.Execute(os.Stdout, u)
}

Output:

Name: Alice, Age: 30

Dot notation (.Field) accesses struct fields passed as data.


Loops with range

data := []string{"Go", "Python", "Rust"}

tmpl := `Languages:
{{range .}}- {{.}}
{{end}}`

t := template.Must(template.New("list").Parse(tmpl))
t.Execute(os.Stdout, data)

Output:

Languages:
- Go
- Python
- Rust

{{range .}} loops over slices or arrays.


Conditionals with if, else, with

tmpl := `
{{if .Admin}}Welcome Admin {{.Name}}{{else}}Welcome User {{.Name}}{{end}}
`

data := map[string]interface{}{
    "Name":  "John",
    "Admin": true,
}
t := template.Must(template.New("cond").Parse(tmpl))
t.Execute(os.Stdout, data)

Output:

Welcome Admin John

Templates support if, else, with blocks just like in control structures.


html/template – Safe HTML Rendering

import (
    "html/template"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    tmpl := `<h1>Hello, {{.}}</h1>`
    t := template.Must(template.New("html").Parse(tmpl))
    t.Execute(w, "<b>John</b>")
}

Output:

<h1>Hello, &lt;b&gt;John&lt;/b&gt;</h1>

html/template automatically escapes HTML to prevent XSS attacks.


Registering Custom Functions

func ToUpper(s string) string {
    return strings.ToUpper(s)
}

func main() {
    funcMap := template.FuncMap{
        "toupper": ToUpper,
    }

    tmpl := `{{toupper .}}`
    t := template.Must(template.New("func").Funcs(funcMap).Parse(tmpl))
    t.Execute(os.Stdout, "hello")
}

Output:

HELLO

Use Funcs() to register custom transformation logic.


text/template vs html/template

Featuretext/templatehtml/template
OutputPlain textHTML with auto-escaping
Use CaseCLI, emails, logsWeb pages, HTML emails
SecurityNo escapingPrevents XSS attacks

Best Practices

PracticeWhy It Matters
Use html/template for webAvoids injection attacks via auto-escaping
Handle errors with Must or checkPrevents silent failures
Avoid logic-heavy templatesMaintain separation of logic and view
Use FuncMap for utilitiesEnables cleaner templates

Summary – Recap & Next Steps

Go’s template system provides a safe, flexible, and idiomatic way to generate dynamic text or HTML output. It’s built into the standard library and suited for everything from emails to web pages.

Key Takeaways:

  • Use text/template for plain output, html/template for safe HTML
  • Templates support loops, conditionals, and custom functions
  • Templates are fast, secure, and easy to integrate into Go apps

Next: Dive into Parsing Templates from Files, Template Inheritance, or Using Templates in Go Web Frameworks.


FAQs – Go Templates

What is {{.}} in Go templates?
It refers to the current data context passed to the template.

How do I escape HTML in templates?
Use html/template which escapes by default to prevent XSS.

Can templates include loops and if-else logic?
Yes. Templates support {{range}}, {{if}}, {{else}}, and {{with}}.

What’s the difference between text/template and html/template?
html/template auto-escapes HTML; text/template does not.

Can I use functions inside Go templates?
Yes, by registering custom functions with Funcs() and using them in your templates.


Share Now :
Share

Go – Templates

Or Copy Link

CONTENTS
Scroll to Top