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

How to Pass Multiple Data Objects to a Go Template?

DDD
DDDOriginal
2024-12-29 05:58:10279browse

How to Pass Multiple Data Objects to a Go Template?

Passing Multiple Data Objects to Go Template

Introduction
Enhancing the functionality of Go templates often involves passing multiple data objects to them. This allows us to display complex data structures in our templates.

Data Composition for Template Data
To pass multiple data objects, we can compose them into a single value:

Using a Struct
Create a struct with exported fields for the data objects:

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

Example:

data := &Data{results, []int{1, 2, 3}}

Using a Map
Create a map with string keys for named data values:

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

Example:

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

Accessing Data in Templates
In the template, we can access the composed data:

{{range .Results}}
    Name: {{.Name}}
{{end}}
{{range $key, $val := .Results}}
    {{$key}}: {{$val.Name}}
{{end}}
{{.Other}}

Example Execution

GetTemplate("list").Execute(w, data)
GetTemplate("list").Execute(w, m)

Alternative Approaches
While the above methods are widely used, other options include:

  • Passing data through channels
  • Registering custom functions

The above is the detailed content of How to 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