How to transfer some data to a Go template?

I want to pass two data objects to a Go template. One is the result of a MongoDB query, and the other is an integer array.

MongoDB request: -

var results []User
sess, db := GetDatabase()
defer sess.Close()
c := db.C("user")
err := c.Find(nil).All(&results)

I want to send a "result" and an int array through the following code

GetTemplate("list").Execute(w,???????)

If there is only db result, we can use it as

GetTemplate("list").Execute(w,results)

and in the template we could access it {{.Name}}, etc. (where Name is the field of the [] User structure)

Tell us how to transfer this data and how to access it in the template.

+4
source share
2 answers

You can wrap some data intended for a template in structor in map.

Example with struct:

type Data struct {
    Results []User // Must be exported!
    Other   []int  // Must be exported!
}

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

, , , , :

data := struct {
    Results []User // Must be exported!
    Other   []int  // Must be exported!
}{results, []int{1, 2, 3}}

map:

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

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

, string , . "results" "other" (, , , struct , ).

[]User {{.Results}} int {{.Other}}.

, , :

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

, , Execute.

tmpl.Execute Writer struct

type Inventory struct {
    Material string
    Count    uint
}

items := Inventory{"trouser", 1}    
if err := GetTemplate("list").Execute(w, items); err != nil {
    // ... do your work
}
+1

Source: https://habr.com/ru/post/1627437/


All Articles