数据类似
```go
data[users]=[]user{
{id:1,name:"test",groupid:3},
{id:2,name:"test2",groupid:2}
}
data[groups]=map[int]group{
3:{id:3,name:"管理组"},
2:{id:2,name:"普通组"}
}
```
希望输出
```html
<tr>
<td>test</td>
<td>管理组</td>
<tr>
<tr>
<td>test2</td>
<td>普通组</td>
<tr>
```
问题在于,在template里,循环users的时候,要把groupid转换成对应的name,怎么样转换比较高效
可参考以下代码
```go
package main
import (
"html/template"
"os"
)
func main() {
users := []struct {
Id int
Name string
GroupId int
}{
{Id: 1, Name: "test", GroupId: 3},
{Id: 2, Name: "test2", GroupId: 2},
}
groups := map[int]struct {
Id int
Name string
}{
3: {Id: 3, Name: "管理组"},
2: {Id: 2, Name: "普通组"},
}
tmplTxt := `{{range .}}
<tr>
<td>{{.Name}}</td>
<td>{{.GroupId | getGroupName}}</td>
</tr>
{{end}}`
t := template.Must(template.New("outHTML").
Funcs(template.FuncMap{"getGroupName": func(gpId int) string {
return groups[gpId].Name
}}).Parse(tmplTxt))
t.Execute(os.Stdout, users)
}
```
#6
更多评论