
Go 的 HTML 模板支持通过 $index, $value := $slice 语法在 {{range}} 中同时获取元素索引和值,无需额外函数或嵌套逻辑,直接实现类似 Go 原生 for i, v := range slice 的语义。
go 的 html 模板支持通过 `$index, $value := $slice` 语法在 `{{range}}` 中同时获取元素索引和值,无需额外函数或嵌套逻辑,直接实现类似 go 原生 `for i, v := range slice` 的语义。
在 Go 的 html/template 中,{{range}} 动作默认仅将当前项(.)置入作用域,但可通过显式声明两个变量——索引(通常命名为 $index)和元素值(如 $article)——来同时访问位置与数据。该语法严格遵循 $index, $value := $collection 格式,且必须按此顺序声明:索引在前,值在后。
以下是一个典型用例,展示如何渲染带序号的文章列表:
{{ range $index, $article := $.Articles }}
<a href="/articles/{{ $article.ID }}" class="list-group-item">
<p class="list-group-item-text">序号:{{ add1 $index }}</p>
<h4 class="list-group-item-heading">{{ $article.Title }}</h4>
<p class="list-group-item-text">{{ $article.Body | truncate 120 }}</p>
<p class="list-group-item-text">{{ .FormatDate $article.CreatedAt }}</p>
</a>
{{ end }}✅ 关键要点:
- $index 是从 0 开始的整数,对应切片原始索引;
- 变量名 $index 和 $article 是任意的(可替换为 $i, $v 等),但必须以 $ 开头,以区别于模板内普通字段;
- 若只需索引而无需值,仍需保留占位变量(如 $index, $_ := $slice),否则语法报错;
- 注意:$index 作用域仅限于 {{range}} 内部,外部不可访问;
- 如需从 1 开始编号,可配合自定义函数(如 add1)或使用 {{add $index 1}}(需已注册 add 函数)。
此外,若数据结构为 map 或 channel,$index 将分别表示键(map)或递增序号(channel),行为略有差异,建议始终对 slice 使用该模式以保证可预测性。合理利用 $index 能显著提升模板表达力,避免冗余后端预处理逻辑。
立即学习“前端免费学习笔记(深入)”;



















