我有一个.thtml文件:
...
<div>
<p>{{.Something}}</p> <!-- It works here! -->
{{range ...}}
<p>{{.Something}}</p> <!-- It DOESN't work here! -->
{{end}}
</div>
...
如果我在.thtml文件中使用.Something
的值,它可以正常工作,但如果在{{range ...}}
块中以相同的方式使用它,它就无法工作。
我该如何使用它?
答案 0 :(得分:1)
光标由{{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>
...