Skip to content
Related Articles

Related Articles

Templates in GoLang
  • Last Updated : 16 Jul, 2020

Template in Golang is a robust feature to create dynamic content or show customized output to the user. Golang has two packages with templates:

  • text/template
  • html/template

There are mainly 3 parts of a template which are as follows:

1. Actions

They are data evaluations, control structures like loops or functions. Actions are delimited by {{ and }} where the root element is shown up by using dot operator(.) within braces, {{.}}. These actions control how the final output will look.
To place the value of a field of current struct object, prefix the field name by a dot operator(.) within curly braces like {{.FieldName}}. The data which is evaluated inside it is called pipeline.

2. Conditions

if-else construct can also be used within a template. For example, to execute a template only when the condition is true, we can use the following syntax:

{{if .condition}} temp_0 {{else if .condition}} temp_1 {{else}} temp_2 {{end}}

This will execute the first template, temp_0, if the first condition is true if the second condition holds true, then the second template, temp_1, will execute, else the third template, temp_2, will execute.



3. Loops

Iterations can also be used within a template using the range action. Syntax for looping within a template is:

{{range .List}} temp_0 {{else}} temp_1 {{end}}

Here List should be an array, map or slice which if has length 0, then template temp_1 will be executed, else it iterates through the elements on List.

The input format for a template should be of a UTF-8-encoded format. Any other text outside is printed as it is to the standard output. The predefined variable os.Stdout refers to the standard output to print out the merged data. The Execute() function takes any value which implements the Writer interface and applies a parsed template to the specified data object.

Example 1:




// Golang program to illustrate the
// concept of text/templates
package main
  
import (
    "os"
    "fmt"
    "text/template"
)
  
// declaring a struct
type Student struct{
  
    // declaring fields which are
    // exported and accessible 
    // outside of package as they 
    // begin with a capital letter
    Name string
    Marks int64
}
  
// main function
func main() {
  
    // defining an object of struct
    std1 := Student{"Vani", 94}
      
    // "New" creates a new template
    // with name passed as argument
    tmp1 := template.New("Template_1")
  
    // "Parse" parses a string into a template
    tmp1, _ = tmp1.Parse("Hello {{.Name}}, your marks are {{.Marks}}%!")
      
    // standard output to print merged data
    err := tmp1.Execute(os.Stdout, std1)
      
    // if there is no error, 
    // prints the output
        if err != nil {
                fmt.Println(err)
        }
}

Output:

Hello Vani, your marks are 94%!

The package template “html/template” provides same interface to the “text/template” but rather having a text output, it implements data-driven templates for generating HTML output. This HTML output is safe against any external code injection.

Example 2:

“index.html” file:




<!DOCTYPE html>
<html>
<head>
<title>Results</title>
</head>
<body>
<h1>Hello, {{.Name}}, ID number: {{.Id}}</h1>
<p>
  You have scored {{.Marks}}!
<p>
</body>
</html>

“main.go” file:




// Golang program to illustrate the
// concept of html/templates
package main
  
import (
    "html/template"
    "os"
)
  
// declaring struct
type Student struct {
  
    // defining struct fields
    Name string
    Marks int
    Id string
}
  
// main function
func main() {
      
    // defining struct instance
    std1 := Student{"Vani", 94, "20024"}
  
    // Parsing the required html
    // file in same directory
    t, err := template.ParseFiles("index.html")
  
    // standard output to print merged data
    err = t.Execute(os.Stdout, std1)
}

Output:




<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Hello, Vani, ID number: 20024</h1>
<p>
  You have scored 94!
<p>
</body>
</html>

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :