Golang html模板索引

时间:2016-07-01 12:52:34

标签: html go

当我使用{{range}}对切片进行范围调整时,我可以使用数据管道实例化多个元素。但我看不出如何找到范围内每个元素的索引。随着我们可以:

for i, _ := range x {}

我们可以用模板做类似的事情吗?

2 个答案:

答案 0 :(得分:1)

我想以下工作

{{ range $key, $val := . }}
<strong>{{ $key }}</strong>: {{ $val }}
{{ end }}

答案 1 :(得分:1)

这是我的例子。希望它能帮到你

 {{ range $index,$article := $articles }}

    <a href="/articles/{{ $article.Id }}" class="list-group-item">
      <p class="list-group-item-text">{{ $index }}</p>  // index here start with 0
      <h4 class="list-group-item-heading">{{ $article.Title }}</h4>
      <p class="list-group-item-text">{{ $article.Body }}</p>
      <p class="list-group-item-text">{{ .FormatDate $article.CreatedOn }}</p>

    </a>
  {{ end }}