Go to alternative for python loop.last

I am looking for a loop for an array with Go patterns, and I want to add an extra row to the last element in the loop.

In python, I can do

{% for host in hosts %} {{ host }}{% if loop.last %} ;{% endif %} {% endfor %} 

We are looking for the same with Go, below is a fragment of the Go equivalent.

 {{ range $host := $hosts }} {{$host}} {{ end }} 

Thanks.

+8
source share
3 answers

If the list is not empty, then the Python fragment prints a semicolon after the last element. You can achieve the same result in Go by surrounding the range if you need to check if there is at least one element in the slice and print it; out of cycle.

 {{if $hosts}}{{range $host := $hosts}} {{$host}} {{ end }} ;{{end}} 

This snippet works because you add it to the end of the last element. A more general solution requires a special template function. Here is an example function:

 func last(v interface{}, i int) (bool, error) { rv := reflect.ValueOf(v) if rv.Kind() != reflect.Slice { return false, errors.New("not a slice") } return rv.Len()-1 == i, nil } 

and here is how to use it in a template:

 {{range $i, $host := $hosts }} {{$host}}{{if last $hosts $i}} ;{{end}} {{ end }} 

I posted a working example of a custom function on the playground.

+3
source

An alternative is to determine the decrement function, for example,

  "dec": func(n int) int { return n - 1 }, 

Then you can use the dec function to calculate the last element, for example,

 {{$last := dec (len $hosts)}} {{range $i, $host := $hosts}} {{$host}}{{if eq $i $last}} ;{{end}} {{end}} 

Of course, it would be easier if Go patterns allowed for subtraction so you could write {{$last := (len $hosts) - 1}} . In the end, they insist on having a space before or after a space with a minus sign, so why not allow simple arithmetic?

0
source

pongo2 is syntax support for a Django template (which is similar to Jinja2's). Your template code will work in pongo2 with a few changes; see this example on the playground.

-1
source

Source: https://habr.com/ru/post/1207954/


All Articles