Adding to variable when using range (like for, foreach)

Here is an example:

  1. The initial variable is a number. At first it’s 0.
{{ $rackedUpDowntime := 0 }}
  1. Then, for each entry, I wanted to add up the numbers like this…
{{ range $inactive }}
      {{ $t := (time .Params.ResolvedWhen) }}
      {{ $timeDiff := (sub $t.Unix .Date.Unix) }}
      {{ $diffInMin := (div $timeDiff 60) }}

      {{ $timeDiff }}

      {{ add $rackedUpDowntime $timeDiff }}
    {{ end }}
  1. To show like this:
      {{ add $rackedUpDowntime $timeDiff }}
    {{ end }}

...

{{ $rackedUpDowntime }}
```

but I get 0. How should I add these numbers together?

It’s currently not possible to update variables in a range loop. It’s coming in the future, but it isn’t here yet.

In the mean time, you can use Scratch variables to achieve your goal.

An example of scratch variables in your situation looks like this (untested of course):

{{ range $inactive }}
    {{ $t := (time .Params.ResolvedWhen) }}
    {{ $timeDiff := (sub $t.Unix .Date.Unix) }}
    {{ $diffInMin := (div $timeDiff 60) }}

    {{ $timeDiff }}

    {{ $.Scratch.Add "rackedUpDowntime" $timeDiff }}
{{ end }}

<p>Total downtime is: {{ $.Scratch.Get "rackedUpDownTime" }}.</p>
1 Like

This works but I had to edit the capitalization. It was rackedUpDowntime on one line and rackedUpDownTime on the other :slight_smile:

Thank you! :pray:

This is coming in the soon to be relased Go 1.11 – so fairly soon.

1 Like