在THTML文件中使用Go .Variable内部范围块

时间:2017-07-01 20:04:40

标签: html go cgo go-templates

我有一个.thtml文件:

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

如果我在.thtml文件中使用.Something的值,它可以正常工作,但如果在{{range ...}}块中以相同的方式使用它,它就无法工作。

我该如何使用它?

1 个答案:

答案 0 :(得分:1)

光标由{{range}}修改。将光标指定给变量并在该范围内使用该变量。

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

playground example

如果此代码段中的起始光标是模板的起始值,则使用$变量:

...
<div>
    <p>{{$.Something}}</p>     <!-- the variable $ is the starting value for the template -->    
    {{range ...}}
        <p>{{$.Something}}</p>    
    {{end}}
</div>
...