如何将多个值从模板传递到模板?
时间:2023-04-02
浏览:460
作者:佚名
学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《如何将多个值从模板传递到模板?》,以下内容主要包含golang等知识点,如果你正在学习或准备学习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}}
正确答案
从 doc
中引用,动作text/template的语法{{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 模板?](https://stackoverflow.com/questions/35224066/how-to-pass-multiple-data- to-go-template/35224244#35224244)
所以我们应该将这些数据包装到一个结构或映射中。但是我们不能在模板中编写 Go
代码。我们可以做的是注册一个函数,我们将这些数据传递给该函数,该函数可以进行“打包”并返回一个值,现在我们可以将其传递给{{template}}动作。
这是一个示例包装器,它只是将这些包装到地图中:
func Wrap(shops []Destination, cityName, regionName string) map[string]interface{} {
return map[string]interface{}{
"Shops": shops,
"CityName": cityName,
"RegionName": regionName,
}
}
可以使用该Template.Funcs()方法注册自定义函数,不要忘记在解析模板文本之前必须这样做。
这是一个修改后的模板,它调用此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)
}
输出(在Go Playground上试试):
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}]
本篇关于《如何将多个值从模板传递到模板?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
