How to use Templates in Go

<title>Level up from zero to ` + hero + `</title>

Israel Miles
Level Up Coding
Published in
7 min readFeb 25, 2021

--

From Pixabay

Go has grown to be one of the most popular general programming languages in the modern tech ecosystem. One of the reasons Go is my own personal favorite language is because it encourages the developer to “think like a programmer”. While there are a growing number of fantastic libraries and packages, Go is modular enough that it’s often easier (if not better) to create your own custom programming solutions with just the standard library rather than relying on third parties *cough, Python, cough*.

This can especially be seen with templates — which allow you to customize output in a dynamic but structured manner. Templates can be used to display information on a web page or send out emails to a customer base. In this tutorial we will cover templates within the following sections:

  • Basics of templates in Go
  • Passing composite data structures into templates
  • Passing functions into templates

Templates are extremely useful when it comes to web development in Go, so let’s get started!

Basics of Templates in Go

Templates allow us to display data output dynamically. Say for example we wanted to insert a variable into a body of HTML, we can do so using templates. By using back-ticks, we can insert the first and last variables into the <h1></h1> tags within the code snippet below.

Running the program would then give us…

$ go build
$ ./main
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Izzy Miles thinks Go is awesome!</h1>
</body>
</html>

$

But this can only get us so far. What if we have many templates to process on the fly? Do we really need to implement logic to parse every one ourselves? This is where Go’s standard library comes into play —…

--

--

Software Engineer at Audible. Remote Work Proponent and writer of anything that gets a rant out of me.