Templating is a powerful feature that allows you to create customized and dynamic output. For example, if you a creating a web page, you can use templating to inject the username of a user from the database to the front-end interface.

In Go, you have two templating packages: text/template and html/template. Although they both provide a closely similar interface, the html/template package can generate HTML code and minimize security flaws in the application.

In this article, we will discuss how to use the templating packages in Go.

Components of a Template

There are three principal components of a template:

Actions

Data evaluations refer to functions, loops, dan data evaluations. They are denoted by the use of double curly braces as {{.}} A dot element inside a template represents the root element. Using template actions, you can determine the final output based on a specific expression.

Conditions

You can also include if…else constructs in a template. An example of if…else check in a template is as shown:

{{if .condition}} // run this {{else if .condition}} // run this block {{else}} // run me {{end}}

The above syntax will run the first block if the first condition is true, otherwise, check condition 2 and if true, run the second block. If none are true, run the else block.

Loops

Loops are also supported inside a template. For example, you can iterate over a slice inside a template as shown:

{{range .var}} // do {{else}} // do {{end}}

The var can be any iterable type such as an array, slice, or map.

Creating, Parsing and Using Templates

There are three main useful methods when working with templates:

  1. New – creates a new undefined template.
  2. Parse – parses as specified template string and returns a template.
  3. Execute – applies a parsed template to a data structure and writes the result.

An example of how to use these methods is as shown:

package main

import (


    “log”


    “os”


    “text/template”

)

// define stuct to hold the data

type Users struct {


    // fields


    Id, Age int


    Name    string

}

func main() {

// create an instance of the object


    user1 := Users{1, 28, “Rick Tewk”}


    temp := template.New(“template”)


    temp, _ = temp.Parse(“Hi  {{.Name}}, you are at index {{.Id}} and {{.Age}} years old!”)


    err := temp.Execute(os.Stdout, user1)


    if err != nil {


        log.Fatal(err)


    }

}

The above example uses the New, Parse and Execute methods from the text/template package to parse and execute a template.

Html/template

The html/template package provides a similar interface as the text/template package. However, it uses data-driven templates for output.

An example is as shown:

Create an index.html file as:



<html lang=“en”>

<head>


    <meta charset=“UTF-8”>


    <meta http-equiv=“X-UA-Compatible” content=“IE=edge”>


    <meta name=“viewport” content=“width=device-width, initial-scale=1.0”>


    <title>HTML Tempating</title>

</head>

<body>


    <h1>


        <p>Hi {{.Name}}, you are at index {{.Id}} and {{.Age}}</p>


    </h1>

</body>

</html>

We can then add templating inside the go file as:

package main

import (


    “fmt”


    “os”


    “html/template”

)

// // define stuct to hold the data

type Users struct {


    // fields


    Id, Age int


    Name    string

}

func main() {


    user1 := Users{1, 28, “Rick Tewk”}


    temp, err := template.ParseFiles(“index.html”)


    err = temp.Execute(os.Stdout, user1)


    fmt.Println(err)

}

In the above example, we use the ParseFiles() method to add templating to the index file. The code above should return:



<html lang=“en”>

<head>


    <meta charset=“UTF-8”>


    <meta http-equiv=“X-UA-Compatible” content=“IE=edge”>


    <meta name=“viewport” content=“width=device-width, initial-scale=1.0”>


    <title>HTML Tempating</title>

</head>

<body>


    <h1>


        <p>Hi Rick Tewk, you are at index 1 and 28</p>


    </h1>

</body>

</html>

Notice the HTML files the information from the struct in the Go file

Conclusion

In this article, we explored how to include dynamic content using text/template and html/template packages in Go.

Thanks for reading!

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/john-150×150.png621352a7e2a58.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list