Home >Backend Development >Golang >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!