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
Patricia ArquetteOriginal
2024-12-29 06:35:09471browse

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
}

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
}

In the template:

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

{{range .Other}}
    {{.}}
{{end}}

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},
}

Pass the map to the template execution:

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

In the template:

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

{{range .Other}}
    {{.}}
{{end}}

Using a Slice:

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

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

Pass the slice to the template execution:

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

In the template:

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

Other: {{index . 1}}

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!

Statement:
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