Sling Academy
Home/Golang/Working with Template Engines Using the `text/template` and `html/template` Packages

Working with Template Engines Using the `text/template` and `html/template` Packages

Last updated: November 26, 2024

Understanding Template Engines in Go

In Go, template engines are powerful tools that allow you to dynamically generate content. The two main packages used for templating in Go are text/template and html/template. While they share similar features, html/template provides additional protection against cross-site scripting (XSS) attacks, making it preferable for rendering HTML content.

Using text/template

The text/template package is designed for generating non-HTML text content. Here, we'll see how you can use this package to create dynamic messages:

package main

import (
    "os"
    "text/template"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    tmpl, err := template.New("example").Parse("Hello, my name is {{ .Name }} and I am {{ .Age }} years old.")
    if err != nil {
        panic(err)
    }

    person := Person{"John Doe", 28}
    err = tmpl.Execute(os.Stdout, person)
    if err != nil {
        panic(err)
    }
}

In this example, we define a simple template that prints a greeting message with placeholders for the name and age.

Using html/template

The html/template package is similar to text/template but with extra measures to safely handle HTML. Here is how you can use it:

package main

import (
    "html/template"
    "os"
)

type Product struct {
    Name  string
    Price float64
}

func main() {
    tmpl, err := template.New("webpage").Parse("<div><h1>Buy our {{ .Name }}!</h1><p>Only ${{ .Price }}</p></div>")
    if err != nil {
        panic(err)
    }

    product := Product{"Gopher Plushie", 19.99}
    err = tmpl.Execute(os.Stdout, product)
    if err != nil {
        panic(err)
    }
}

Here, any content outputted into the template is properly escaped to ensure it is safe for rendering in a web environment.

Differences and Use Cases

While both packages can be used similarly, html/template is built explicitly to handle scenarios where user input might be included in the output, ensuring it is sanitized and safe to render in a web browser.

  • text/template is best when generating plain text formats or rendering templates not meant for direct client-side consumption.
  • html/template should be used anytime you are working with HTML output for web applications.

Conclusion

The use of templates in Go allows for clean separation of your static and dynamic content. Understanding when to utilize text/template versus html/template based on context and content type ensures you harness their full potential for creating safe and efficient Go applications.

Next Article: Managing Signal Handling with the `os/signal` Package in Go

Previous Article: Exploring Priority Queues Using the `container/heap` Package in Go

Series: Working with Core package in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant