Scoping a variable outside of and if statement (or two)

Given the following:

{{ $btotal := $anumber }}
{{ $gtotal := $btotal }}
{{ if isset .Params "other" }}
    {{ if eq .Params.other true }}
        {{ $ntotal := $anothernumber }}
        {{ $gtotal := math.Round (div (add $btotal $ntotal) 2) }}
    {{ end }}
{{ end }}
{{ $gtotal }}

And assuming all page parameters are present and set to true…

This produces the first value of $gtotal and ignores the new value set in the if statements. I’m sure the explanation is much simpler than my question. Is this about setting the scope of the variable?

Basically what I’m wanting to do is set the value of a variable, but then if another parameter is present, redefine that first variable with some math operations.

Until then, Scratch is your tool

1 Like

Thank you, @bep!

Here is my new code, for any further searches by anyone:

{{ $btotal := $anumber }}
{{ .Scratch.Set "gtotal" $btotal }}
{{ if isset .Params "other" }}
    {{ if eq .Params.other true }}
        {{ $ntotal := $anothernumber }}
        {{ .Scratch.Set "gtotal" (math.Round (div (add $btotal $ntotal) 2)) }}
    {{ end }}
{{ end }}
{{ .Scratch.Get "gtotal" }}
1 Like