I want to pass two data objects to Go Template. One is a MongoDB query result and other is an integer array.
MongoDB Query:-
var results []User
sess, db := GetDatabase()
defer sess.Close()
c := db.C("user")
err := c.Find(nil).All(&results)
I want to sent 'result' and an int array through following code
GetTemplate("list").Execute(w,???????)
If there is only db result, we could use it as
GetTemplate("list").Execute(w,results)
and in template we could access it {{.Name}} etc. (where Name is a struct field of []User)
Please tell me how to pass these data and how to access them in template.
You should define a struct populated with the database results query, then assign that struct to the
Execute
method.tmpl.Execute
require aWriter
interface and astruct
You may wrap multiple data intended for the template in a
struct
or in amap
.Example with a
struct
:Also note that a new, named type is not required, you could also use an anonymous struct literal, which could look like this:
Example with a
map
:Note that using a map, it is not required to use capitalized
string
s as keys, e.g. you could've used"results"
and"other"
too (but in my opinion it's better to use keys with capital starting letters, should you move tostruct
sometimes in the future, you would have less corrections to make).In both cases you may refer to the
[]User
results with{{.Results}}
and to the additional int slice with{{.Other}}
.So for example to range over the users: