template里的range,如何使用其他map里的index

hsyan2008 · 2017-05-04 11:16:28 · 1986 次点击

可参考以下代码

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 .}}
        
            {{.Name}}
            {{.GroupId | getGroupName}}
        
        {{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
更多评论

group,map的key为user中的group 的id。

#1

刚才疏漏了,groups的结构修改了。这种情况下template里怎么写比较方便呢

#2