BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Templates

Go 1.23

Go has a powerful built-in template engine for generating text or HTML. This example shows how to parse templates, inject data, use actions like range/if, and execute them.

Code

package main

import (
    "os"
    "text/template"
)

type Inventory struct {
    Material string
    Count    uint
}

func main() {
    // 1. Define a simple template
    // {{.Count}} accesses the Count field of the data.
    // {{- ... -}} trims whitespace.
    const tmpl = `
{{- .Count }} items are made of {{ .Material }}
{{ if gt .Count 100 -}}
It is well stocked!
{{- else -}}
We need to restock.
{{- end }}
`

    // 2. Create and Parse
    // Must handle errors in production code.
    t, err := template.New("inventory").Parse(tmpl)
    if err != nil {
        panic(err)
    }

    // 3. Execute with Data
    sweaters := Inventory{"wool", 17}
    err = t.Execute(os.Stdout, sweaters)
    if err != nil {
        panic(err)
    }

    // 4. Execute with different Data
    // Templates are reusable.
    t.Execute(os.Stdout, Inventory{"cotton", 250})
}

Explanation

Go's text/template and html/template packages provide a robust, data-driven engine for generating textual output by executing a template definition against a specific data structure, such as a struct or a map. This system relies on "actions"—commands enclosed in double curly braces {{...}}—to perform logic like conditional execution, iteration over collections, and pipeline processing, where the output of one function is seamlessly passed as the input to the next. The html/template package specifically is engineered for web security, automatically applying context-aware escaping to the injected data to neutralize potential Cross-Site Scripting (XSS) vectors, making it the standard choice for rendering HTML responses in web applications.

The "dot" (.) concept is central to template execution, representing the current context or data item being processed; as the template engine traverses nested structures or iterates over slices using the range action, the value of . dynamically changes to reflect the immediate data scope. This design allows for the creation of highly reusable and modular templates that can adapt to varying data hierarchies, while the ability to define custom functions via a FuncMap extends the language's capabilities, enabling developers to perform complex formatting or logic directly within the presentation layer.

  • Actions: {{ .Field }} to access data.
  • Control Flow: {{ if }}, {{ range }}, {{ with }}.
  • Pipelines: {{ .Value | func }} passes data to functions.
  • Security: Always use html/template for web output to prevent XSS.

Code Breakdown

17
Template syntax. The double curly braces denote an action. '.Count' accesses the Count field of the struct passed to Execute. The dash '{{-' tells the engine to trim the preceding whitespace/newline.
18
Conditional logic. 'gt' is a built-in function meaning "greater than". 'if gt .Count 100' checks if the count is > 100. This logic happens at render time.
27
Parsing the template. We create a new template named "inventory" and parse the string string constant. In a real app, you might use 'ParseFiles' to load from disk.
34
Executing the template. We pass 'os.Stdout' as the writer (so it prints to console) and 'sweaters' as the data object. The template engine uses reflection to read the fields of the struct.