text/template issue: Is there a way to identity the last element of ranging array?

9,266 views
Skip to first unread message

Googol Lee

unread,
Jun 18, 2012, 7:04:26 AM6/18/12
to golan...@googlegroups.com
For example:

func main() {
    t := template.Must(template.New("abc").Parse("{{ range . }}{{ . }}, {{ end }}."))                                                                        
    a := []string{"Alice", "Bob", "Cherry", "Dark"}
    t.Execute(os.Stdout, a)
}

The output is:
Alice, Bob, Cherry, Dark, .

But I want to get:
Alice, Bob, Cherry, Dark.

Notice after the last element "Dark" expect dot, not comma.

I know I can write a function to do this, but is there a easy way to do it in template?

Martin Schnabel

unread,
Jun 18, 2012, 7:21:56 AM6/18/12
to golan...@googlegroups.com


from http://go.pkgdoc.org/text/template:

If a "range" action initializes a variable, the variable is set to the
successive elements of the iteration. Also, a "range" may declare two
variables, separated by a comma:

$index, $element := pipeline

then you can use the index to check for the first element. like this:
http://play.golang.org/p/-pR3Bn6efy

Googol Lee

unread,
Jun 18, 2012, 7:31:23 AM6/18/12
to golan...@googlegroups.com
I know how to check first element. But how to check the last one?

roger peppe

unread,
Jun 18, 2012, 7:46:36 AM6/18/12
to Googol Lee, golan...@googlegroups.com
On 18 June 2012 12:31, Googol Lee <goog...@gmail.com> wrote:
> I know how to check first element. But how to check the last one?

It seems to me that Martin's answer solved your problem admirably.

But if you really want to check for the last element, there are
a few ways of doing it, by defining your own functions.

Here are a couple of examples:

http://play.golang.org/p/NWhyfft8Ba
http://play.golang.org/p/Y-CZ2TBSGU

Carlos Castillo

unread,
Jun 18, 2012, 10:20:58 PM6/18/12
to golan...@googlegroups.com, Googol Lee
If you are defining functions in templates you could just use strings.Join

http://play.golang.org/p/3tnjtT8-Qw

Googol Lee

unread,
Jun 18, 2012, 11:28:52 PM6/18/12
to golan...@googlegroups.com, Googol Lee
Thank you. The last function seems pretty good.

On Monday, June 18, 2012 7:46:36 PM UTC+8, rog wrote:

Googol Lee

unread,
Jun 19, 2012, 12:05:49 AM6/19/12
to golan...@googlegroups.com, Googol Lee
The last function is wired. Template parser pass a string to last, and the Len of value "a" is the string length, not array.


On Monday, June 18, 2012 7:46:36 PM UTC+8, rog wrote:

roger peppe

unread,
Jun 19, 2012, 6:24:53 AM6/19/12
to Googol Lee, golan...@googlegroups.com
Yes, the call I made only worked by coincidence...
The intention was to pass the slice into the last
function, not the element. This is better:
http://play.golang.org/p/VM4rSuEG2A
Reply all
Reply to author
Forward
0 new messages