Doing add and subtract directly in Go templates

---
date: Oct 30, 2023
tags:
- GoLang
language: English
---
This post is more than 2 years old. If this is a technical post, the post will most likely not working, but feel free to try it and see if it works.

Well, You Know

You know, this year happened way too much that I just realized I haven’t posted for a really long time. My last post is in Feburary, so O haven’t posted in over half a year! So I decided to post something today on solving some stupid things I encountered and figured out during my work: Pure arithmetic operations in Go templates.

Calculations needed, but no access

During the work, I got something that I needed to craft a Go template to generate a report using a utility, but at the mean time I needed to perform some simple calculations during the process, so I went to check the official documentation, I realized there are no arithmetic operations in native Go Template. Normally, If you want to do something like this, what you will need to do is the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
funcMap := template.FuncMap{
"add": func(i int) int {
return i + 1
},
}

tmpl, err := template.New("test").Funcs(funcMap).Parse(`{{add 1}}`)
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, nil)
if err != nil {
panic(err)
}

In this case, the output would be 2.

addition and subtraction… with 1

So, what should I do to do that natively with Go template? After a quick search, I found this Stack Overflow solution; this solution enables adds and subtractions by one with limitations for a non-negative solutions:

And this is how they works:

add and subtraction!

After I knew how it worked, I decided to modify it so that I could add or subtract any number with it, like the following:

In this way, I can finally generate my report normally. A sample can be seen here.