Given the template
{{range $i, $e := .SomeField}}
{{if $i}}, {{end}}
$e.TheString
{{end}}
This can output
one, two, three
If, however, I want to output
one, two, and three
I'd need to know which is the last element in the range above.
I can set a variable that holds the length of the array .SomeField, but that will always be 3, and the $i value above will only ever get to 2. And you can't perform arithmetic in templates from what I've seen.
Is detecting the last value in a template range possible? Cheers.
This is probably not the most elegant solution but it's the best I could find:
http://play.golang.org/p/MT91mLqk1s
Note: You can also do it without reflect using the
len
function (credit to Russ Cox): http://play.golang.org/p/V94BPN0uKDc.f.
We had same problem today when working with format in docker inspect command. The easiest way to get the last element without patching Docker was (the expression has been split into lines for ease of reading):
So in our case, we needed the image name without registry address and version. For example, image name like registry.domain.local/images/nginx:latest becomes nginx.
P.S: You need Go >= 1.11 to do the job (https://github.com/golang/go/issues/10608)