当前位置: > > > > 如何在模板之间传递多个值?
如何在模板之间传递多个值?
来源:stackoverflow
2024-04-21 16:54:37
0浏览
收藏
小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《如何在模板之间传递多个值?》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!
问题内容
我的 city 结构是这样的:
type city struct {
id int
name string
regions []region
}
region 结构是:
type region struct {
id int
name string
shops []destination
masters []master
educationcenters []destination
}
主要是我尝试这样做:
tpl.executetemplate(reswriter,"cities.gohtml",citywithsomedata)
是否可以在模板内执行类似的操作?
{{range .}}
{{$city:=.Name}}
{{range .Regions}}
{{$region:=.Name}}
{{template "data" .Shops $city $region}}
{{end}}
{{end}}
正确答案
引用的文档,{{template}}操作的语法:
{{template "name"}}
the template with the specified name is executed with nil data.
{{template "name" pipeline}}
the template with the specified name is executed with dot set
to the value of the pipeline.
这意味着您可以将一个可选数据传递给模板执行,而不是更多。如果要传递多个值,则必须将它们包装成传递的某个值。详情见
所以我们应该将这些数据包装到一个结构体或一个映射中。但我们不能在模板中编写go代码。我们可以做的是注册一个函数来传递这些数据,该函数可以执行“打包”并返回一个值,现在我们可以将其传递给 {{template}} 操作。
这是一个示例包装器,它只是将它们打包到地图中:
func wrap(shops []destination, cityname, regionname string) map[string]interface{} {
return map[string]interface{}{
"shops": shops,
"cityname": cityname,
"regionname": regionname,
}
}
可以使用 方法注册自定义函数,并且不要忘记在解析模板文本之前必须执行此操作。
这是一个修改后的模板,它调用此 wrap() 函数来生成单个值:
const src = `
{{define "data"}}
city: {{.cityname}}, region: {{.regionname}}, shops: {{.shops}}
{{end}}
{{- range . -}}
{{$city:=.name}}
{{- range .regions -}}
{{$region:=.name}}
{{- template "data" (wrap .shops $city $region) -}}
{{end}}
{{- end}}`
这是一个可运行的示例,展示了这些操作:
t := template.must(template.new("cities.gohtml").funcs(template.funcmap{
"wrap": wrap,
}).parse(src))
citywithsomedata := []city{
{
name: "citya",
regions: []region{
{name: "ca-ra", shops: []destination{{"ca-ra-sa"}, {"ca-ra-sb"}}},
{name: "ca-rb", shops: []destination{{"ca-rb-sa"}, {"ca-rb-sb"}}},
},
},
{
name: "cityb",
regions: []region{
{name: "cb-ra", shops: []destination{{"cb-ra-sa"}, {"cb-ra-sb"}}},
{name: "cb-rb", shops: []destination{{"cb-rb-sa"}, {"cb-rb-sb"}}},
},
},
}
if err := t.executetemplate(os.stdout, "cities.gohtml", citywithsomedata); err != nil {
panic(err)
}
输出(在 上尝试):
city: citya, region: ca-ra, shops: [{ca-ra-sa} {ca-ra-sb}]
city: citya, region: ca-rb, shops: [{ca-rb-sa} {ca-rb-sb}]
city: cityb, region: cb-ra, shops: [{cb-ra-sa} {cb-ra-sb}]
city: cityb, region: cb-rb, shops: [{cb-rb-sa} {cb-rb-sb}]
我猜 citywithsomedata 是一个切片,如果是这样,请尝试这样的操作:
type viewmodel struct {
list []city
}
然后,在您的模板中:
{{range .List}}
{{$city:=.Name}}
{{range .Regions}}
{{$region:=.Name}}
{{template "data" .Shops $city $region}}
{{end}}
{{end}}
理论要掌握,实操不能落!以上关于《如何在模板之间传递多个值?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注米云公众号吧!
