Go - Templates



In Go, templates refer to a powerful feature used for generating dynamic content. They are used for formatting and producing output, such as HTML for web applications.

Go provides two types of templates, They are:

  • Text Templates (from text/template package): Ideal for generating plain text output like emails or configuration files.
  • HTML Templates (from html/template package): It is designed for generating HTML and includes automatic escaping to prevent security vulnerabilities like cross-site scripting (XSS).

Templates use placeholders, also known as actions, enclosed within {{ }}. These actions allow you to inject dynamic data, iterate over collections, use conditional logic, and call functions.

Let's go through an example for better understanding of this concept −

Example

A simple template is created with a placeholder {{.Name}}. The program passes a map with the key Name and value Revathi to the template.

package main
import (
   "os"
   "text/template"
)
func main() {
   tmpl, _ := template.New("example").Parse("Hello, {{.Name}}!")
   tmpl.Execute(os.Stdout, map[string]string{"Name": "Revathi"})
}

Following is the output to the above program −

Hello, Revathi!

As Go (Golang) provides a powerful templating engine in its text/template and html/template packages. These packages allow you to generate textual or HTML output by combining data with templates.

Below is an overview of how to use Go templates −

Basic Template Syntax

Go templates use double curly braces ({{ }}) as placeholders to inject data, iterate, or apply logic (e.g., conditionals, variables, loops ) into templates.

Syntax

Following is the syntax of the Basic Template −

{{.}}              
{{.FieldName}} 
{{"constant text"}}

Example

A template is defined with a placeholder {{.}}. The program passes the string "World" to the template, which replaces the placeholder.

package main
import (
   "os"
   "text/template"
)
func main() {
   // Define a template
   const tmpl = "Hello, {{.}}!"
   
   // Parse the template
   t, err := template.New("test").Parse(tmpl)
   if err != nil {
   	 panic(err)
   }  
   // Execute the template with data
   err = t.Execute(os.Stdout, "World")
   if err != nil {
   	 panic(err)
   }
}

It will generate the following output −

Hello, World!

Using Structs in Templates

You can pass a Go struct to a template and reference its fields (.FieldName) to inject structured data dynamically into the output.

Syntax

Following is the syntax of the Templates using Structs −

{{.FieldName}}      
{{.Nested.Field}}   
Loops and Conditionals

Example

A Person struct is passed to the template. The template accesses the struct fields (Name and Age) using {{.Name}} and {{.Age}}.

package main
import (
   "os"
   "text/template"
)
type Person struct {
   Name string
   Age  int
}
func main() {
   const tmpl = "Name: {{.Name}}, Age: {{.Age}}"
   
   t, err := template.New("test").Parse(tmpl)
   if err != nil {
      panic(err)
   }

   p := Person{Name: "Revathi", Age: 24}
   err = t.Execute(os.Stdout, p)
   if err != nil {
      panic(err)
   }
}

It will generate the following output −

Name: Revathi, Age: 24

Loops and Conditionals

The Templates support control flow by using "range" to iterate over slices or maps and "if" to add conditional logic, tailoring the output based on data.

Syntax

Following is the syntax of the Template using Loops and Conditionals −

{{range .}}         
  {{.}}            
{{end}}

{{if .Condition}}   
  {{.FieldName}}     
{{else}}             
  {{.OtherField}}  
{{end}}

Example

The template uses "range" to iterate over a slice of Person structs and "if" to render only active users.

package main
import (
   "os"
   "text/template"
)
func main() {
       const tmpl = `{{range .}}{{if .Active}}Name: {{.Name}}, Age: {{.Age}}
{{end}}{{end}}`

   t, err := template.New("test").Parse(tmpl)
   if err != nil {
      panic(err)
   }

   type Person struct {
      Name   string
      Age    int
      Active bool
   }
   people := []Person{
      {Name: "Revathi", Age: 25, Active: true},
      {Name: "Tapas", Age: 35, Active: false},
      {Name: "Vivek", Age: 27, Active: true},
   }

   err = t.Execute(os.Stdout, people)
   if err != nil {
      panic(err)
   }
} 

It will generate the following output −

Name: Revathi, Age: 25
Name: Vivek, Age: 27

HTML Templates

The html/template package is similar to text/template but it escapes HTML to prevent XSS attacks.

Syntax

Following is the syntax of the HTML Templates −

{{.FieldName}}       
{{html .FieldName}} 
{{. | safe}}         

Example

An HTML template is defined with placeholders for Title and Content. The program passes a struct with these fields, and the html/template package escapes the content to prevent XSS.

package main
import (
   "html/template"
   "os"
)
func main() {
    const tmpl = ` 
<html>
<body>
<h1>{{.Title}}</h1>
<p>{{.Content}}</p>
</body>
</html> 
`
   t, err := template.New("webpage").Parse(tmpl)
   if err != nil {
      panic(err)
   }
   data := struct {
      Title   string
      Content string
   }{
      Title:   "Welcome to Go Templates",
      Content: "This is an example of using html/template in Go.",
   }

   err = t.Execute(os.Stdout, data)
   if err != nil {
      panic(err)
   }
}

It will generate the following output −

<html>
<body>
<h1>Welcome to Go Templates</h1>
<p>This is an example of using html/template in Go.</p>
</body>
</html>
Advertisements