2016-04-05 11:27



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):

{{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??////////////  
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • duannai5879 duannai5879 5年前

    You can access the Communication field just like other fields.


    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,

    Then your template could be,

    {{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>

    See these in Go Playground

    点赞 评论 复制链接分享