Go—calculations for billing

Hi all!

At the moment I am switching all several projects from Middleman to Hugo. Works like a charme.

As I am completely new to golang, there is one big question left:

For billing purposes we need something like this:

  {{ range $index, $item := .Params.items }}
    <td>{{ add $index 1 }}</td>
    <td>{{ $item.description }}</td>
    <td>{{ $item.quantity }}</td>
    <td>{{ $item.price_per_item }} $</td>
    <td>{{ mul $item.quantity $item.price_per_item }} $</td>
  {{ $total := add $sum $sum }}
  {{ end }}

{{ $total }} $
  • Is it possible to format numbers in a currency format?
  • Is it possible to do something like $total := add $sum $sum to calculate the total and write it to a global variable?

Thank you very much in advance!

Looks like there is some cool currency-related functionality in Go’s library, but nothing to my knowledge in Hugo.

That said, there is a set of handy math operators that you might be able to leverage in order to get your desired result…

This might be helpful for formatting: https://gohugo.io/functions/replacere/

Though you might want to search the forums on using it, because, though not reflected in the docs, Hugo uses a particular Regex syntax

Nope, unfortunately. Currency formatting has come up earlier here and formatting number was discussed earlier here.

So far these features are still on the wish list of a few users, so your best bet is to create something custom.

1 Like

Thank you all very much for your help. That’s very useful links. The calculation should be no problem then.

Just one further inquiry: How is it possible to count up the $total variable in the loop and read it out as a global variable after the loop ended. (Sorry—I’m really completely new to Go as stated above).

Thank you!

Use Scratch. Using the $ (as I do below) allows you to take the global scope (or top-level node as it’s referred to in docs).

In your loop, do {{ $.Scratch.Set "globalTotal" $total }} to assign the Scratch variable “globalTotal” to be the value of your $total variable.
And then outside your loop do {{ $.Scratch.Get "globalTotal" }} to print it, or use the .Scratch.Get function in another function (for instance, to do math on or otherwise)

1 Like

Perfect! Thanks a lot. That function was new to me.