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
Release: 2024-12-29 05:58:10
Original
278 people have browsed it

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
}
Copy after login

Example:

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

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

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

Example:

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

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

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

Example Execution

GetTemplate("list").Execute(w, data)
GetTemplate("list").Execute(w, m)
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template