Doing add and subtract directly in Go templates
---date: Oct 30, 2023
tags:
- GoLang
language: English
---
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 | funcMap := template.FuncMap{ |
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:
- For addition, using
{{ len (printf "a%*s" $number "") }}
to add by 1; - For subtractionion, using
{{ len (slice (printf "%*s" $number "") 1) }}
to subtraction by 1.
And this is how they works:
- For addition, this works by constructing a string with
$number
of character""
and add a single charactera
and then calculate the length; - similarly, for subtraction, this works by constructing a string with
$number
of character""
and slicing the string with one letter, and then calculating the length.
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:
- For addition:
{{ len (printf "%*s%*s" $numbera "" $numberb "") }}
- For subtraction:
{{ len (slice (printf "%*s" $numbera "") $numberb) }}
In this way, I can finally generate my report normally. A sample can be seen here.