Go模板中的嵌套范围
nested range in Go template
我有这样的结构
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"`
}
每个用户都会有两种通信结构,如
[
{
"Type": "MOBILE",
"Value": "12121212"
},
{
"Type": "Email",
"Value": "Some@email.com"
}
]
在我的模板中,我想将它们显示在 table 中。我正在获取用户结构值,但无法获取通信结构值
HTML 模板文件(部分代码):
<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>
您可以像访问其他字段一样访问通信字段。
{{$val.Communication}}
因为您希望每个条目都在单独的 <td>
中,所以如果您可以将它们放在 map
而不是 slice
中会更容易。您可以为此使用如下函数。
sliceToMap := func(s []*Communication) map[string]string {
comms := map[string]string{}
for _, c := range s {
comms[c.Type] = c.Value
}
return comms
}
您可以将此注册为自定义函数以在模板中使用,
t := template.Must(template.New("").Funcs(template.FuncMap{
"SliceToMap": sliceToMap,
}).Parse(src))
那么你的模板可以是,
<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>
中查看这些内容
我有这样的结构
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"`
}
每个用户都会有两种通信结构,如
[
{
"Type": "MOBILE",
"Value": "12121212"
},
{
"Type": "Email",
"Value": "Some@email.com"
}
]
在我的模板中,我想将它们显示在 table 中。我正在获取用户结构值,但无法获取通信结构值
HTML 模板文件(部分代码):
<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>
您可以像访问其他字段一样访问通信字段。
{{$val.Communication}}
因为您希望每个条目都在单独的 <td>
中,所以如果您可以将它们放在 map
而不是 slice
中会更容易。您可以为此使用如下函数。
sliceToMap := func(s []*Communication) map[string]string {
comms := map[string]string{}
for _, c := range s {
comms[c.Type] = c.Value
}
return comms
}
您可以将此注册为自定义函数以在模板中使用,
t := template.Must(template.New("").Funcs(template.FuncMap{
"SliceToMap": sliceToMap,
}).Parse(src))
那么你的模板可以是,
<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>
中查看这些内容