Templating in Go with Example

Published on January 27, 2020 59 sec read

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. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Follow Buy me a coffeeBuy me a coffee

Leave a Reply

Your email address will not be published. Required fields are marked *