Template and incrementing counters in range

7,554 views
Skip to first unread message

OmarShariffDontLikeIt

unread,
Mar 8, 2012, 4:38:58 AM3/8/12
to golang-nuts
I have a template which iterates over []DataStruct. In my template I
have something like the following:

{{range data}}
<p id="p_{{count}} />
{{end}}

I want to generate an ID that is based on an integer that increases
with each iteration of the range. I've read the template documentation
but couldn't find anything that suggests a built-in way to do this,
and using {{$counter := $counter + 1}} spat out an error about the "+"
symbol. The only course of action I can think of is to map a function
that increments a value: {{$counter := Increment $counter}} or
something.

Can anyone think of a better way to do this?

Cheers!
Ben

Andrew Gerrand

unread,
Mar 8, 2012, 7:08:01 AM3/8/12
to OmarShariffDontLikeIt, golang-nuts
`{{range $index, $value := .slice}}`

http://play.golang.org/p/eFShvWjTnP

Andrew

Rob 'Commander' Pike

unread,
Mar 8, 2012, 7:08:52 AM3/8/12
to OmarShariffDontLikeIt, golang-nuts
Make count a function, or .Count a method of the data type.

Of course, if you're willing to reset to zero on each run of the
range, the index will do.

{{range $index, $element := data}} <p id="p+{{$index}}/> {{end}}

-rob

OmarShariffDontLikeIt

unread,
Mar 8, 2012, 7:23:21 AM3/8/12
to golang-nuts
You know, I was confused as to why range didn't have an index, turns
out it does! Thats exactly what I wanted.

Even found the line in the documentation now too. Bah!

Cheers!

saub...@gmail.com

unread,
Apr 1, 2015, 11:34:38 AM4/1/15
to golan...@googlegroups.com, omarsharif...@gmail.com
How do i increment value each time in range ? please guide
Reply all
Reply to author
Forward
0 new messages