dqg17080 2016-04-05 11:27 采纳率: 0%
浏览 169
已采纳

Go模板中的嵌套范围

I have structure like these

type Users struct{  
    Name           string           `json:"Name,omitempty"`  
    Gender         string           `json:"Gender,omitempty"`  
    Communication  []*Communication `json:"Communication,omitempty"`  
}  

type Communication struct {  
    Type  string `json:"Type,omitempty"`  
    Value string `json:"Value,omitempty"`  
}  

every user will have two communication structure like

[
    {
        "Type": "MOBILE",
        "Value": "12121212"
    },
    {
        "Type": "Email",
        "Value": "Some@email.com"
    }
]  

In my template i want to display them in a table. iam getting the User structure values, but could not get the communication structure values

HTML Template file (partial code):

<tbody>  
{{range $key, $val := .Users}}   
<td style="text-align: center;">{{$val.Name}}</td>  
<td style="text-align: center;">{{$val.Gender}}</td>  
///////How to display communication values here??////////////  
{{end}}  
</tbody>
  • 写回答

1条回答 默认 最新

  • duannai5879 2016-04-05 11:59
    关注

    You can access the Communication field just like other fields.

    {{$val.Communication}}

    Since you want each these entries in separate <td>s its easier if you could put them in a map instead of a slice. You could use a function like below for that.

    sliceToMap := func(s []*Communication) map[string]string {
        comms := map[string]string{}
    
        for _, c := range s {
            comms[c.Type] = c.Value
        }
    
        return comms
    }
    

    You can register this as a custom function to be used in the template,

    t := template.Must(template.New("").Funcs(template.FuncMap{
        "SliceToMap": sliceToMap,
    }).Parse(src))
    

    Then your template could be,

    <tbody>  
    {{range $key, $val := .Users}}   
    <td style="text-align: center;">{{$val.Name}}</td>  
    <td style="text-align: center;">{{$val.Gender}}</td> 
    
    {{$comms := SliceToMap $val.Communication}}
    
    <td style="text-align: center;">{{index $comms "mobile"}}</td>
    <td style="text-align: center;">{{index $comms "email"}}</td>
    
    {{end}}  
    </tbody>
    

    See these in Go Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大