Go logo

GoLand

A cross-platform Go IDE with extended support for JavaScript, TypeScript, and databases

Features Tutorials

Go templates made easy

Go ships with its own template engine, split into two packages, text/template and html/template. These packages are similar in functionality, with the difference that html/template allows a user to generate HTML code that is safe against code injection, making it suitable for use on web pages and emails. These packages are also used in other applications such as the configuration for Helm, the Kubernetes package manager, assisting with code generation and much more.

Let’s take a look at an example below.
Create a project and place the following code in a main.go file:

package main

import (
	"io/ioutil"
	"os"
	"text/template"
)

type (
	Location struct {
		Street  string
		ZipCode string
	}

	User struct {
		Username  string
		Locations map[string]Location
	}

	UsersPage struct {
		Title string
		Users []User
	}
)

func main() {
	t, err := template.New("UsersPage").Parse("index.html")
	if err != nil {
		panic(err)
	}

	p := UsersPage{
		Title: "Users location",
		Users: []User{
			{
				Username: "Florin",
				Locations: map[string]Location{
					"Home": {
						Street:  "GoLand",
						ZipCode: "2018.3",
					},
				},
			},
		},
	}

	err = t.Execute(os.Stdout, p)
	if err != nil {
		panic(err)
	}
}

Then, place the following template code in a new file named index.html:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
</head>
<body>

</body>
</html>

Now let’s start to add some output to our page so that we can deliver the data to it.
Normally you’d start typing something like “<title>{{.” and expect the IDE to be smart enough and give you completion options for the options after the dot.

This is where GoLand comes to help us.
We can now specify the type beforehand by invoking the “Specify dot type” action via Alt + Enter and select the type from the list of types available in the project.

Go Template

This doesn’t work only for structure fields as the “Title” of the page works, but it works for slices, slice elements, and even for elements that are part of a map and are a more complex type.

Go Template - 2

Besides completion options, once you specify the type of the dot in the template, other functionality such as Navigate to Declaration, Find Usages, or even Rename refactoring will work as the IDE has enough information to complete these actions.

Go Template - 3

That’s it for today. We learned how we can get better code assistance from the IDE when using the built-in Go template engine and work with it more effectively.

Please let us know your feedback in the comments section below, on Twitter, or on our issue tracker, and tell us what would you like to learn more about in future articles.

image description