How to use Go template syntax?

0126

Go template syntax is a powerful feature in the Go programming language that allows you to generate text output based on data structures. It is commonly used in web applications, configuration files, and command-line tools. Here’s a concise guide on how to use Go template syntax effectively.

Basic Structure

A Go template consists of plain text interspersed with actions enclosed in double curly braces {{ }}. Here are the key components:

  1. Variables: You can access fields of a data structure.

    {{ .Name }}  // Accesses the Name field of the current data context
  2. Actions: Perform operations like loops and conditionals.

    • Range: Iterate over slices or maps.

      {{ range .Items }}
        {{ . }}  // Outputs each item in the Items slice
      {{ end }}
    • If: Conditional statements.

      {{ if .IsActive }}
        Active
      {{ else }}
        Inactive
      {{ end }}
  3. Functions: Use built-in functions for formatting and manipulation.

    {{ len .Items }}  // Gets the length of the Items slice

Example Usage

Here’s a simple example of using Go templates in a Go program:

package main

import (
    "os"
    "text/template"
)

type User struct {
    Name  string
    Age   int
    Hobbies []string
}

func main() {
    user := User{
        Name: "Alice",
        Age:  30,
        Hobbies: []string{"Reading", "Hiking", "Coding"},
    }

    tmpl := `Name: {{ .Name }}
Age: {{ .Age }}
Hobbies:
{{ range .Hobbies }}
- {{ . }}
{{ end }}`

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

Output

When you run the above program, it will produce:

Name: Alice
Age: 30
Hobbies:
- Reading
- Hiking
- Coding

Tips for Using Go Templates

  • Escape HTML: Use {{ .Field | html }} to prevent XSS attacks when rendering user input.
  • Custom Functions: You can define and use custom functions in templates for more complex logic.
  • Error Handling: Always check for errors when executing templates to handle any issues gracefully.

Further Learning

To explore more about Go templates, consider checking the official Go documentation on text/template and html/template for web applications.

If you have any more questions or need further clarification, feel free to ask!

0 Comments

no data
Be the first to share your comment!