Templating in Go with Example

In this tutorial, we are going to learn templating in Go. Using html/template package we’ll do templating. It provides a rich templating language for HTML templates. By default, Go protect the XSS attacks.

Table of Contents

  1. Parsing Templates
  2. Execute a Template
  3. Create Struct & Template
  4. Parse Template and Run

Parsing Templates

At first, let’s see the way to parse template:

// way 1
tmpl := template.Must(template.ParseFiles("hello.html"))

// way 2
tmpl, err := template.ParseFiles("hello.html")

Execute a Template

We have to execute a template in the request handler like:

func(w http.ResponseWriter, r *http.Request) {
    tmpl.Execute(w, "the data")
}

Create Struct & Template

We’re going to pass simple data to HTML template. Let’s create a Person struct:

type Person struct {
    Name string
    Email string
}

Create a file called hello.html in the root directory of the project. Then paste this code:

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Go Template</title>
</head>
<body>

Hello {{.Name}}, Your email address: {{.Email}}

</body>
</html>

In Go, we can get passed variable data like {{variable}}.

Parse Template and Run

Let’s see the complete example of parsing data to HTML template:

main.go
package main

import (
    "log"
    "html/template"
    "net/http"
)

type Person struct {
    Name string
    Email string
}

func main() {
    tmpl, err := template.ParseFiles("hello.html")
    if err != nil {
        log.Fatal("Parse: ", err)
        return
    }

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        data := Person{
            Name: "Md Obydullah",
            Email: "[email protected]",
        }
        tmpl.Execute(w, data)
    })
    http.ListenAndServe(":80", nil)
}

To run this project, just type this command:

go run main.go
The article is over. Thanks for reading. ?

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.