在 THTML 文件中使用 Go .Variable inside range 块
Use Go .Variable inside range block in THTML file
我有一个 .thtml 文件:
...
<div>
<p>{{.Something}}</p> <!-- It works here! -->
{{range ...}}
<p>{{.Something}}</p> <!-- It DOESN't work here! -->
{{end}}
</div>
...
如果我在 .thtml 文件中使用 .Something
的值,它工作正常,但如果在 {{range ...}}
块中以相同的方式使用它,它就不起作用。
如何使用?
光标被{{range}}修改。将光标分配给一个变量并在范围内使用该变量。
...
<div>
<p>{{.Something}}</p>
{{$x := .}} <!-- assign cursor to variable $x -->
{{range ...}}
<p>{{$x.Something}}</p>
{{end}}
</div>
...
如果此代码段中的起始光标是模板的起始值,则使用 $
变量:
...
<div>
<p>{{$.Something}}</p> <!-- the variable $ is the starting value for the template -->
{{range ...}}
<p>{{$.Something}}</p>
{{end}}
</div>
...
我有一个 .thtml 文件:
...
<div>
<p>{{.Something}}</p> <!-- It works here! -->
{{range ...}}
<p>{{.Something}}</p> <!-- It DOESN't work here! -->
{{end}}
</div>
...
如果我在 .thtml 文件中使用 .Something
的值,它工作正常,但如果在 {{range ...}}
块中以相同的方式使用它,它就不起作用。
如何使用?
光标被{{range}}修改。将光标分配给一个变量并在范围内使用该变量。
...
<div>
<p>{{.Something}}</p>
{{$x := .}} <!-- assign cursor to variable $x -->
{{range ...}}
<p>{{$x.Something}}</p>
{{end}}
</div>
...
如果此代码段中的起始光标是模板的起始值,则使用 $
变量:
...
<div>
<p>{{$.Something}}</p> <!-- the variable $ is the starting value for the template -->
{{range ...}}
<p>{{$.Something}}</p>
{{end}}
</div>
...