
- Go - Home
- Go - Overview
- Go - Environment Setup
- Go - Program Structure
- Go - Basic Syntax
- Go - Data Types
- Go - Variables
- Go - Constants
- Go - Identifiers
- Go - Keywords
- Go - Operators
- Go - Arithmetic Operators
- Go - Assignment Operators
- Go - Relational Operators
- Go - Logical Operators
- Go - Bitwise Operators
- Go - Miscellaneous Operators
- Go - Operators Precedence
- Go Decision Making
- Go - Decision Making
- Go - If Statement
- Go - If Else Statement
- Go - Nested If Statements
- Go - Switch Statement
- Go - Select Statement
- Go Control Flow Statements
- Go - For Loop
- Go - Nested for Loops
- Go - Break Statement
- Go - Continue Statement
- Go - Goto Statement
- Go Functions
- Go - Functions
- Go - Call by Value
- Go - Call by Reference
- Go - Functions as Values
- Go - Function Closure
- Go - Function Method
- Go - Anonymous function
- Go Strings
- Go - Strings
- Go - String Length
- Go - String Concatenation
- Go - Compare Strings
- Go - Split String
- Go - Substring Extraction
- Go - String Replacement
- Go - String Interpolation
- Go - Parse Date Strings
- Go Arrays
- Go - Arrays
- Go - Multidimensional Arrays
- Go - Multidimensional Arrays
- Go - Passing Arrays to Functions
- Go - Pointers
- Go - Pointers
- Go - Array of pointers
- Go - Pointer to pointer
- Go - Passing pointers to functions
- Go Advanced Control Structures
- Go - Scope Rules
- Go - Dereferencing Pointer
- Go - Structures
- Go - Slice
- Go - Slice of Slices
- Go - Range
- Go - Maps
- Go - Recursion
- Go - Type Casting
- Go - Interfaces
- Go - Type Assertion
- Go - Error Handling
- Go - Concurrency
- Go - Regular Expression
- Go - Inheritance
- Go - Packages
- Go - Templates
- Go - Reflection
- Go - Generics
- Go File Handling
- Go - Read File By Word
- Go - Read File By Line
- Go - Read CSV Files
- Go - Delete File
- Go - Rename & Move File
- Go - Truncate a File
- Go - File Read-Write Mode W/O Truncation
- Go Miscellaneous
- Go - defer Keyword
- Go - Fmt Package
- Go - Zero Value
- Go - Import
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>