Rendering templates in Golang

Shan Shaji
2 min readJan 28, 2023

Rendering templates in Golang is a powerful feature that allows developers to separate presentation logic from the business logic of their application. This approach makes it easy to maintain and update the visual appearance of the application without affecting the underlying logic. In this article, we will discuss how to render templates in Golang using the built-in html/template package.

note: this is a basic example for rendering templates in golang.

  1. Creating a template: The first step is to create the template that we want to use to render our data. The template can be written in any text editor and should be saved with a .tmpl extension. For example, let's create a simple template called hello.tmpl that displays a greeting message:
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>{{.Message}}</h1>
</body>
</html>
  1. Parsing the template: Once we have created the template, we need to parse it using the html/template package. This can be done by calling the template.ParseFiles function, passing in the path to the template file as a parameter. For example:
tmpl, err := template.ParseFiles("hello.tmpl")
if err != nil {
log.Fatal(err)
}
  1. Creating a data model: The next step is to create a data model that will be used to populate the template. This can be any struct that contains the data that we want to display. For example, let’s create a struct called Greeting that contains a single field called Message:
type Greeting struct {
Message string
}
  1. Executing the template: Once we have parsed the template and created the data model, we can execute the template by calling the Execute method and passing in the data model as a parameter. For example:
data := Greeting{Message: "Hello World"}
if err := tmpl.Execute(w, data); err != nil {
log.Fatal(err)
}

This is a basic example of how to render templates in Golang using the html/template package. There are many other features and options available, such as template inheritance, template functions, and more. The html/template package is a very powerful and flexible tool for rendering templates in Golang, and it is widely used in many web applications.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Shan Shaji
Shan Shaji

Written by Shan Shaji

Skilled in Flutter, React, MongoDB, Express, and Typescript. Experienced with Flutter architectures, state management, Firebase, and cloud functions.

No responses yet

Write a response