I'm looking to loop over an array with Go templates and I want to add an extra string to the last item in the loop.
In python, I can do
{% for host in hosts %}
{{ host }}{% if loop.last %} ;{% endif %}
{% endfor %}
Looking to achieve same thing with Go, below is the snippet of the Go equivalent.
{{ range $host := $hosts }}
{{$host}}
{{ end }}
Thanks.
If the list is not empty, then the Python snippet prints a semicolon following the last item. You can achieve the same result in Go by surrounding the range with an if to check to see if there's at least one element in the slice and printing the ; outside of the loop.
This snippet works because you are adding to the end of the last item. A more general solution requires a custom template function. Here's an example function:
and here's how to use it in the template:
I posted an a working example of the custom function to the playground.