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>

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