The last item in the pattern range

Given the pattern:

{{range $i, $e := .SomeField}} {{if $i}}, {{end}} $e.TheString {{end}} 

This may output:

 one, two, three 

If, however, I want to output:

 one, two, and three 

I need to know what is the last element in the above range.

I can set a variable that contains the length of the .SomeField array, but it will always be 3, and the value of $i above will only be when it is 2. And you cannot do arithmetic in the templates from what I saw.

Is it possible to determine the last value in a range of patterns? Greetings.

+9
source share
2 answers

This is probably not the most elegant solution, but it is the best I could find:

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

 package main import ( "os" "reflect" "text/template" ) var fns = template.FuncMap{ "last": func(x int, a interface{}) bool { return x == reflect.ValueOf(a).Len() - 1 }, } func main() { t := template.Must(template.New("abc").Funcs(fns).Parse(`{{range $i, $e := .}}{{if $i}}, {{end}}{{if last $i $}}and {{end}}{{$e}}{{end}}.`)) a := []string{"one", "two", "three"} t.Execute(os.Stdout, a) } 

Note: You can also do this without hesitation using the len function (credit for Russ Cox): http://play.golang.org/p/V94BPN0uKD

cf

+14
source

Today we had the same problem when working with the format in the docker inspect command. The easiest way to get the last item without a Docker fix was (the expression was broken into lines for readability):

 {{ $image := "" }} {{ range split .ContainerImageName "/" }} {{ $image = . }}{{ end }} {{ index (split $image ":") 0 }} 

So, in our case, we needed the image name without the address and registry version. For example, the name of the image, for example, registry.domain.local / images / nginx: the latter becomes nginx.

PS: You need Go> = 1.11 to get the job done ( https://github.com/golang/go/issues/10608 )

PPS: The question was about the Go template, but for those who had the same problems with Docker, here are some configuration examples:

1) Using the Go template in daemon.json

cat /etc/docker/daemon.json

 { "log-driver": "syslog", "log-opts": { "syslog-address": "udp://127.0.0.1:20627", "tag": "{{ $image := \"\" }}{{ range split .ContainerImageName \"/\" }}{{ $image = . }}{{ end }}{{ index (split $image \":\") 0 }}/{{.Name}}" } 

2) Using the Go pattern with the -f option:

 docker inspect \ -f '{{ $image := "" }}{{ range split .Config.Image "/" }}{{ $image = . }}{{ end }}{{ index (split $image ":") 0 }}' \ <container> 
+1
source

All Articles