Home > Backend Development > Golang > How to Repeat HTML Lines Multiple Times Using Golang Templates?

How to Repeat HTML Lines Multiple Times Using Golang Templates?

DDD
Release: 2024-12-16 07:14:14
Original
513 people have browsed it

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))
Copy after login

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)
Copy after login

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))
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template