Home >Backend Development >Golang >How to Repeat HTML Lines Multiple Times Using Golang Templates?
Iterating HTML in Golang Templates
In Golang, when iterating over a list of elements in a template, you can use the {{range}} action. However, it requires an array or slice to iterate through. To repeat an HTML line multiple times, we can create an empty slice and populate it with either a zero value or specific values.
Using Zero-Value Slice
We can create an empty slice make([]struct{}, n) to represent the number of iterations we need. Then, in the template, we use the {{range}}${} syntax to iterate over the slice. For example:
tmpl := template.Must(template.New("").Parse(` <ul> {{range $idx, $e := .}} <li><a href="/?p={{idx}}">{{$idx}}</a></li> {{end}} </ul>`)) n := 5 tmpl.Execute(w, make([]struct{}, n))
Using Filled Slice
Alternatively, we can fill the slice with specific values. This approach allows us to skip using the index ($idx) in the HTML code. For example:
tmpl := template.Must(template.New("").Parse(` <ul> {{range .}} <li><a href="/?p={{.}}">{{.}}</a></li> {{end}} </ul>`)) values := make([]int, 5) for i := range values { values[i] = i + 1 } tmpl.Execute(w, values)
Using Zero-Value Slice and Custom Function
Another option is to create a custom function that adds 1 to the slice index and returns the result. This allows you to use the slice indices while incrementing the numbers by 1. For example:
tmpl := template.Must(template.New("").Funcs(template.FuncMap{ "Add": func(i int) int { return i + 1 }, }).Parse(` <ul> {{range $idx, $e := .}}{{$idx := (Add $idx)}} <li><a href="/?p={{$idx}}">{{$idx}}</a></li> {{end}} </ul>`)) n := 5 tmpl.Execute(w, make([]struct{}, n))
These approaches provide flexible ways to repeat an HTML line multiple times based on your specific requirements.
The above is the detailed content of How to Repeat HTML Lines Multiple Times Using Golang Templates?. For more information, please follow other related articles on the PHP Chinese website!