0

I am trying to run over an structure of data (slice), and inside the loop I need to check a little thing. For this purpose I use a variable that is set up before the loop, but if a condition is met, this variable must change the value. Ok!! Inside the loop I print the variable and I see how it changes the value... BUT in each iteration of the loop the variable restarts and get the initial value again.

This is my code:

{{range $response := .result}}
    {{$old := "FALSE"}}
    {{range $seat := $response.SeatList}}
       {{$old}} -------
       {{if ne $old $seat.Row}} {{$old := $seat.Row}} {{$old}} ------- {{end}}
    {{end}}
{{end}}

And it prints something like:

FALSE ------- 4 -------
FALSE ------- 4 -------
FALSE ------- 5 -------
FALSE ------- 5 -------
FALSE ------- 6 -------
FALSE ------- 6 -------

When it should print something like:

FALSE ------- 4 -------
4 ------- 
4 ------- 5 -------
5 -------
5 ------- 6 -------
6 -------

I tried too to make {{$old = $seat.Row}} without colon... but I get a sintaxis error unexpected "=" in operand.

Any way to don't restart teh value of the variable?? Thank you.

PS: I am using revel framework.

Eloy Fernández Franco
  • 1,350
  • 1
  • 24
  • 47
  • 2
    Variables in templates cannot be changed. They live till the end of the containing block. If the block gets executed again (because it's in a loop), it will be created again. They also can be shadowed, but their value cannot be changed. – icza Dec 15 '16 at 11:46
  • 2
    Also duplicate of: [How to create a global variable and change in multiple places in golang html/template?](http://stackoverflow.com/questions/36521839/how-to-create-a-global-variable-and-change-in-multiple-places-in-golang-html-tem/36527130#36527130) – icza Dec 15 '16 at 11:48
  • Thanks @icza. Finally I found a solution changing the perspective. – Eloy Fernández Franco Dec 15 '16 at 12:16

0 Answers0