i give a dataset from mysql-database to go-template. the result have multiple rows but all values is one string!?
type Tasks struct {
tid int
pid int
uid int
del int
finisch int
open int
inprocess int
abnahme int
fertig int
finischdatum string
erstellt string
start string
ende string
name string
beschreibung string
}
type Daten struct {
Tabledata []*Tasks
}
d := Daten{}
rows, err := db.Query("SELECT * FROM tasks WHERE pid=? AND del=0", pid)
checkError(err)
defer rows.Close()
rs := make([]*Tasks, 0)
for rows.Next() {
rst := new(Tasks)
err := rows.Scan(&rst.tid, &rst.pid, &rst.uid, &rst.del, &rst.finisch, &rst.open, &rst.inprocess, &rst.abnahme, &rst.fertig, &rst.finischdatum, &rst.erstellt, &rst.start, &rst.ende, &rst.name, &rst.beschreibung)
if err != nil {
log.Println(err)
}
rs = append(rs, rst)
}
d.Tabledata = rs
template:
{{ range $key, $values := .Tabledata }}
<li><strong>{{ $key }}</strong>: </li>
{{range $values}}
{{.}}
{{end}}
{{ end }}
When I look in the first range and give me the $values as one string and the second range is death.
What's my Problem?
In your code, since you didn't tell, I guess the variable 'd' is passed to the template. 'd' is of type Daten and thus contain a field named TableData. This field is a slice of *Tasks. This is why in your template you can loop on it using range.
The range keyword returns two values, the first one, '$key' in your code, is the index of the slice, and the second one, '$values' in your code is the value pointed by TableData[$key]. Because TableData is a slice of type *Tasks, that means $values is of type *Tasks. So not an array nor a slice.
That means, you can't loop on $values because it's not a slice. But, you can access all the exported fields of Tasks. So depending on what you want to display in your template, you can do the following:
// Inside the firts range
<li><strong>{{ $key }}</strong>: </li>
name: $values.Name
open: $values.Open
Note the uppercase on the field's name, in order to access a field it shall be exported, and thus starts with an upper case in the type declaration.