Variables are not set. Why?

Hi,

so i have the following code:

{{$distanceTop := 75}}
{{range  $i, $e := .Params.categories}}

{{$addValue := mul $i 45}}
{{$distanceTop := add 75 $addValue}}

{{$iconcolor := "#000000"}}
{{$icon := "pencil"}}

{{if eq $e "Text1"}}
  {{$iconcolor := "#FF0000"}}
  {{$icon := "cloud"}}
{{else if eq $e "Text2"}}
  {{$iconcolor := "#FF0000"}}
  {{$icon := "cloud"}} 
{{else if eq $e "Text3"}}
  {{$iconcolor := "#FF0000"}}
  {{$icon := "cloud"}}
{{else if eq $e "Text4"}}
  {{$iconcolor := "#FF0000"}}
  {{$icon := "cloud"}}
{{end}}
  <a href="/categories/{{.|urlize}}"><div style="background-color:{{$iconcolor}}; top:{{$distanceTop}}px;"class="format-wrapper">
  <i class='icon-{{$icon}}'></i>
  </div></a>
{{end}}

So the positioning and setting of the variable $distanceTop works well. But the variables $iconcolor and $icon are not set - although parser DOES go into those if clauses ( i tested it by outputting a string there )

For example:
If a post has 2 categories, there appear 2 icons - both are black and have the pencil as symbol - which is the default - which means the $iconcolor and $icon are not set - but what is the problem - why won’t the variables be set properly / as expected?

thx :slight_smile:

That’s a Go scope issue. It is actually running your code and changing the variable, but only inside the context of the if statement as a new variable. When it exits the if statement, the original variable remains unchanged. @bjornerik has submitted a change to Hugo that would enable you to use page level variables which hopefully makes it into an imminent 0.13 release.

1 Like

thank you for the explanation - i put the “div” part into every if statement ( i wanted to avoid this to have less duplicated code ) and now it does what i expected it to in the first step :slight_smile: