-1

I have a .thtml file:

...
<div>
    <p>{{.Something}}</p>        <!-- It works here! -->
    {{range ...}}
        <p>{{.Something}}</p>    <!-- It DOESN't work here! -->
    {{end}}
</div>
...

If I use the value of .Something inside the .thtml file it works fine, but it doesn't work if it is used in the same way inside a {{range ...}} block.

How can I use it?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • I just have to change an existing Go application, but I don't have a technical background in this language. Also, I'll be thankful if someone can edit my question to make it more clear because I don't know the Go language terminology. – ROMANIA_engineer Jul 01 '17 at 20:06

1 Answers1

1

The cursor is modified by {{range}}. Assign the cursor to a variable and use that variable inside the range.

...
<div>
    <p>{{.Something}}</p>        
    {{$x := .}}    <!-- assign cursor to variable $x -->
    {{range ...}}
        <p>{{$x.Something}}</p>    
    {{end}}
</div>
...

playground example

If the starting cursor in this snippet is the starting value of the template, then use the $ variable:

...
<div>
    <p>{{$.Something}}</p>     <!-- the variable $ is the starting value for the template -->    
    {{range ...}}
        <p>{{$.Something}}</p>    
    {{end}}
</div>
...
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
  • Based on this approach, if I just want to use the value for `Something`, is it better to have something like `{{$x := .Something}}` and inside the `{{range ...}}` block to use just `{{$x}}`? – ROMANIA_engineer Jul 01 '17 at 21:05
  • The {{$x := .Something}} will have a very small performance benefit. I recommend using whatever makes the code easiest to understand. – Charlie Tumahai Jul 01 '17 at 22:27