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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

packagemain

import(

"io/ioutil"

"os"

"text/template"

)

type(

Locationstruct{

Street string

ZipCode string

}

Userstruct{

Username string

Locations map[string]Location

}

UsersPagestruct{

Title string

Users[]User

}

)

funcmain(){

message,err:=ioutil.ReadFile("tpl.gohtml")

iferr!=nil{

panic(err)

}

t,err:=template.New("UsersPage").Parse(string(message))

iferr!=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)

iferr!=nil{

panic(err)

}

}

Then, place the following template code in a new file named tpl.gohtml

1

2

3

4

5

6

7

8

9

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

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.

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.

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.