Compute sum of time.Duration

In my previous post on the forum, I asked about the way to convert a string to a time.Duration and thank you I have received a solution then I didn’t find it myself. thank you.

now, I have read the doc about the variables in a golang template and the scope is limited to the current block.

For example, I would like to compute the sum of time.Duration.

{{ $total := time "2000-01-01T00:00:00" }}
{{ range $page := .Pages }}
    {{ $start_at := printf "2000-01-01T%s" $page.Params.start_at | time }}
    {{ $stop_at := printf "2000-01-01T%s" $page.Params.stop_at | time }}
    {{ $duration := $stop_at.Sub $start_at }}
    {{ $total := $total.Add $duration }}
{{ end }}
{{ $total }}

but when I execute this code, I can see that the variable total after the assignation, inside the range is resetted to the initial value.

so in this case, how do you compute a simple sum without a fork of Hugo and a new function ? is it possible?

Thank you so much,

Yes, but you need to use Scratch (use the search in docs) to keep a running total.

Note that this if fixed in the current Go source code – so once Go 1.11 is out all will be sooooo much better.


hi @bep

really great, I have read the doc of scratch and it’s awesome.

thank you so much,