Home > Back-end >  How can I range a slice of array in go template?
How can I range a slice of array in go template?

Time:09-17

For example, I want to range Fields except the last one element.
Maybe like:

{{range $Field := $.Fields[:len $Field - 1]}}

Do I have some approaches?
Thx!

CodePudding user response:

The builtin template slice function almost does what you need. The missing piece is computing the last index of the new slice. To do that, add an addition function to the template:

func add(a, b int) int {
    return a   b
}

Add the function to template before parsing:

 t, err := template.New(name).Funcs(template.FuncMap{"add": add}).Parse(text)

Use the function like this:

  {{range slice $ 0 (add (len $) -1)}}
     {{.}}
  {{end}}

playground example.

  • Related