Search code examples
htmlgocgogo-templates

Use Go .Variable inside range block in THTML file


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?


Solution

  • 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>
    ...