Golang HTML Template ParseFiles and Execute

Golang template parsefiles

Golang HTML Template ParseFiles and Execute, parses the HTML Files, and then Execute it to allow us to display dynamic data with the help of placeholders, that can be replaced with the values at the runtime, by the template engine. The data can also be transformed according to users’ needs.

In this blog, we will take a look at html/template package to create our first template in Golang.

Golang Template HTML

First create a HTML file inside the templates directory.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Go Template</title>
</head>

<body>
    <h1>Hello, {{.Name}}</h1>
    <p>Your College name is {{.College}}</p>
    <p>Your ID is {{.RollNumber}}</p>

</body>

</html>

The index.html file is the template that we will be using in this example. The template has three placeholders {{.Name}}, {{.College}}, and {{.RollNumber}}, whose value will be placed by the template engine at the runtime.

Golang Templates ParseFile and Execute

func renderTemplate(w http.ResponseWriter, r *http.Request) {
	student := Student{
		Name:       "GB",
		College:    "GolangBlogs",
		RollNumber: 1,
	}
	parsedTemplate, _ := template.ParseFiles("Template/index.html")
	err := parsedTemplate.Execute(w, student)
	if err != nil {
		log.Println("Error executing template :", err)
		return
	}
}

In the renderTemplate Function first the student struct is initialized with values.

The Template is then parsed using the ParseFile() function from the html/template package. This creates a new template and parses the filename that is passed as input. This is not necessary to use only HTML extension, while parsing templates we can use any kind of extension like gohtml, etc.

The Parsed template is then executed and the error is handled after that.

Golang Serve html/template

package main

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

const (
	Host = "localhost"
	Port = "8080"
)

type Student struct {
	Name       string
	College    string
	RollNumber int
}

func renderTemplate(w http.ResponseWriter, r *http.Request) {
	student := Student{
		Name:       "GB",
		College:    "GolangBlogs",
		RollNumber: 1,
	}
	parsedTemplate, _ := template.ParseFiles("Template/index.html")
	err := parsedTemplate.Execute(w, student)
	if err != nil {
		log.Println("Error executing template :", err)
		return
	}
}

func main() {
	http.HandleFunc("/", renderTemplate)
	err := http.ListenAndServe(Host+":"+Port, nil)
	if err != nil {
		log.Fatal("Error Starting the HTTP Server :", err)
		return
	}
}

Output:

Golang Template
Golang Template

Follow Golang Gorilla Mux to learn more about Golang Web Development.

Learn more about Golang HTML Template ParseFiles and Execute from Golang.org.

Tags:

Leave a Reply

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