简体   繁体   中英

How do I get the last element of a slice in a golang template

I can get the size of a slice in a template like this

{{$size := len .Things}}

And I can index a slice in a template like this:

{{index .Things 4}}

But

{{index .Things $size}}

gives an "out of range" error because indexing a slice is zero-based.

Do I have do all the function defining things or is there arithmetic available I can use?


Ie how do I do this https://stackoverflow.com/a/22535888 but in a golang template.

Defining a minus function: https://stackoverflow.com/a/24838050/10245

In go templates could be viewed as more "passive" than in other languages or some frameworks. The idea of passive views is that they do not include much logic but get passed all their data in.

So you could pass "LastThing" to your template, which has the last Thing assigned.

This does not answer your question directly but this is just an alternative you could consider.

There is no arithmetic available by default, but you can add this functionality using a FuncMap .

Here's how to add an "add" function that covers this case and other scenarios:

t := template.Must(template.New("").Funcs(template.FuncMap{
    "add": func(a, b int) int { return a + b },
    }).Parse(theTemplate)

Use it in the template like this:

{{index .Things (add $size -1)}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM