Home > Backend Development > Golang > How Can I Pass Multiple Data Objects to a Go Template?

How Can I Pass Multiple Data Objects to a Go Template?

Patricia Arquette
Release: 2024-12-29 06:35:09
Original
485 people have browsed it

How Can I Pass Multiple Data Objects to a Go Template?

Passing Multiple Data to a Go Template

In Go, when populating a template, you can pass a single value, which can be a composite value such as a struct, map, or slice.

To pass multiple data objects to a template:

Using a Struct:

Create a struct that embeds the desired data objects as exported fields:

type Data struct {
    Results []User // MongoDB query result
    Other   []int  // Integer array
}
Copy after login

Pass the struct to the template execution:

data := &Data{results, []int{1, 2, 3}}
if err := GetTemplate("list").Execute(w, data); err != nil {
    // Handle error
}
Copy after login

In the template:

{{range .Results}}
    User name: {{.Name}}
{{end}}

{{range .Other}}
    {{.}}
{{end}}
Copy after login
Copy after login

Using a Map:

Create a map with the data objects as key-value pairs:

m := map[string]interface{}{
    "Results": results,
    "Other":   []int{1, 2, 3},
}
Copy after login

Pass the map to the template execution:

if err := GetTemplate("list").Execute(w, m); err != nil {
    // Handle error
}
Copy after login

In the template:

{{range .Results}}
    User name: {{.Name}}
{{end}}

{{range .Other}}
    {{.}}
{{end}}
Copy after login
Copy after login

Using a Slice:

While less readable, you can also pass a slice of interface{}:

s := []interface{}{
    results,
    []int{1, 2, 3},
}
Copy after login

Pass the slice to the template execution:

if err := GetTemplate("list").Execute(w, s); err != nil {
    // Handle error
}
Copy after login

In the template:

{{range index . 0}}
    User name: {{.Name}}
{{end}}

Other: {{index . 1}}
Copy after login

Note: Custom functions or channels can also be used to pass multiple data objects, but are considered less conventional practices.

The above is the detailed content of How Can I Pass Multiple Data Objects to a Go Template?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template