3 Simple Techniques using Go Templates

Krish S Bhanushali
4 min readJun 9, 2021

Using Go Templates can be quite confusing at the start but once you get used to what all it can do, you will simply love it. Right from printing simple text or parsing the text into an HTML to display it on a web page or to send it via email is what Go Templates can do.

I am going to show you 6 simple tricks in with how does each functionality work and a sample working code of each of those simple tricks in Go with Github Gist Page and Go Playground link.

Let us get started-

1. Using functions in Go templates

You can use functions to do any kind of formatting you need in the template.

Here are some examples where you can use functions in Go Templating:

  • String Manipulation

In Go Templates, you can use any string functions you need to be used in your text/HTML templates. All you need is to use the FuncMap map[string]func which maps your template function to the actual strings library function. For example, please look at line no. 18–20 in the below example.

Just like below, "ToUpper" links to "toUpper”of the strings library function. Now how do you use this "ToUpper" function in your template? You can simply pipe the function to any string you want to manipulate. For example…

--

--

Krish S Bhanushali

Analytic problem solver by birth and programmer by choice. Motivator and spiritual. Portfolio: www.krishbhanushali.me