How to define multiple ranges with text/template 【Go】
Feb 6, 2023
I spent much time solving this problem. I’ll summarize the way in order not to forget about it.
package main
import (
"text/template"
)
func main(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("./root/to/index.html")
data := map[string]interface{}{
"SliceOne": []int{1, 2, 3},
"SliceTwo": []string{"one", "two", "three"},
}
t.Execute(w, data)
}
#and
#View is below
#Slice One:
#{{ range .SliceOne }}
#{{ . }}
#{{ end }}
#Slice Two:
#{{ range .SliceTwo}}
#{{ . }}
#{{ end }}`
It is not necessary to define structs.