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

How Can I Pass Multiple Data Objects to Go Templates?

Susan Sarandon
Susan SarandonOriginal
2024-12-19 21:22:10667browse

How Can I Pass Multiple Data Objects to Go Templates?

Passing Multiple Data to Go Templates

Template execution in Go allows you to pass a single value, but this value can be a composite type containing multiple components. This offers several options for passing and accessing various data objects in the template.

Composite Value Using Struct:

Create a custom struct data type encapsulating the desired data:

type Data struct {
    Results []User
    Other   []int
}

Assign the data and execute the template:

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

In the template, access the MongoDB results as {{.Results}} and the integer array as {{.Other}}.

Composite Value Using Map:

Alternatively, create a map containing the data:

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

Pass the map to the template and access the data using dot notation: {{.Results}} for results and {{.Other}} for the integer array.

Composite Value Using Slice:

A less readable approach is to use a slice containing the data:

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

Index the template data to access the components: {{index . 0}} for results and {{index . 1}} for the integer array.

Additional Notes:

Remember that the data type must be exported to be accessible in the template.

Consider using a struct or map to improve readability and maintainability.

Other approaches exist but are less practical for this specific scenario.

The above is the detailed content of How Can I Pass Multiple Data Objects to Go Templates?. 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