golang

Golang HTML Template

The Go html/template package provides tools and functions for working with templating language in HTML documents. HTML templating is an extensive feature that allows you to add dynamic data from the backend language to the front-end.

Unlike the text/html package in Go, the html/template package cleans the data and escapes all inputs before running it on the client side. This prevents security flaws such code injection using Cross Site Scripting.

Components of a Template

A template is made up of three main components.

Actions

Data evaluations refer to functions, loops, and 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.

Golang HMTL Template

Working with templates in HTML is very straightforward. You can use the template constructs discussed above to determine how you can insert the data.

For example, we can create a list and iterate over each element on the list. We can then pass that information to html template to display the actual on the client side.

An example is as shown below:

package main
import (
    "html/template"
    "log"
    "os"
)

type Users struct {
    Username string
    Expired  bool
}
type Info struct {
    SiteTitle string
    Data      []Users
}

func main() {
    var temp = `
<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>{{.SiteTitle}}</title>
</head>
<body>
    <h1>
        <ul>
            {{range. data}}
                {{if .expired}}
            <li>{{.item}}</li>
                {{else}}
            <li>{{.item}}</li>
        </ul>
    </h1>
</body>
</html>`
    // parse template
    t, err := template.New("users").Parse(temp)
    if err != nil {
        log.Fatal(err)
    }
    data := Info{
        SiteTitle: "HTML Templating",
        Data: []Users{
            {Username: "username1", Expired: true},
            {Username: "username2", Expired: false},
        },
    }
    t.Execute(os.Stdout, data)

}

The above examples use html/template to inject data from the struct to the html template.

Closing

This guide illustrates how to use html/template package to inject dynamic content into HTML file. Check out the html/template package to learn more.

About the author

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