Home >Backend Development >Golang >How can I repeat HTML code multiple times in a Go web application using templates?
In your Go web application, you have a need to output a specific HTML line numerous times, depending on the value of n.
Here's a way to approach this:
In HTML templates, the {{range}} action allows you to iterate over items. However, this action requires a slice, array, or map to work with.
To cater to this requirement, you can pass an empty slice with no allocated memory, such as make([]struct{}, n).
Template Code:
<ul> {{range $idx, $e := .}} <li><a href="/?page={{$idx}}">{{$idx}}</a></li> {{end}} </ul>
Testing the Code:
tmpl := template.Must(template.New("").Parse(templ)) n := 5 if err := tmpl.Execute(os.Stdout, make([]struct{}, n)); err != nil { panic(err) }
Output:
<ul> <li><a href="/?page=0">0</a></li> <li><a href="/?page=1">1</a></li> <li><a href="/?page=2">2</a></li> <li><a href="/?page=3">3</a></li> <li><a href="/?page=4">4</a></li> </ul>
To customize the starting index for the links, you can fill the slice with specific values.
Template Code:
<ul> {{range .}} <li><a href="/?page={{.}}">{{.}}</a></li> {{end}} </ul>
Example Test Code:
tmpl := template.Must(template.New("").Parse(templ)) n := 5 values := make([]int, n) for i := range values { values[i] = (i + 1) * 2 } if err := tmpl.Execute(os.Stdout, values); err != nil { panic(err) }
Output:
<ul> <li><a href="/?page=2">2</a></li> <li><a href="/?page=4">4</a></li> <li><a href="/?page=6">6</a></li> <li><a href="/?page=8">8</a></li> <li><a href="/?page=10">10</a></li> </ul>
Finally, you can use a custom function within the templates to modify the index values as needed.
Template Code:
<ul> {{range $idx, $e := .}}{{$idx := (Add $idx)}} <li><a href="/?page={{$idx}}">{{$idx}}</a></li> {{end}} </ul>
Custom Function:
func Add(i int) int { return i + 1 }
Output:
<ul> <li><a href="/?page=1">1</a></li> <li><a href="/?page=2">2</a></li> <li><a href="/?page=3">3</a></li> <li><a href="/?page=4">4</a></li> <li><a href="/?page=5">5</a></li> </ul>
The above is the detailed content of How can I repeat HTML code multiple times in a Go web application using templates?. For more information, please follow other related articles on the PHP Chinese website!