Passing Multiple Values from Template to Template in Go: A Comprehensive Guide
How can I proficiently transfer multiple values from one template to another in Go? Consider the provided context:
In the main function, I execute a template cities.gohtml with a CityWithSomeData:
tpl.ExecuteTemplate(resWriter, "cities.gohtml", CityWithSomeData)
Within the template, I aim to iterate over the cities and regions to pass data to another template data:
{{range .}} {{$city:=.Name}} {{range .Regions}} {{$region:=.Name}} {{template "data" .Shops $city $region}} {{end}} {{end}}
Solution
According to Go template documentation, the syntax for the {{template}} action allows for passing only one optional data value. To pass multiple values, we need to first encapsulate them into a single value, such as a map or a struct.
Since writing Go code within a template is not feasible, we can register a custom function to perform this task:
func Wrap(shops []Destination, cityName, regionName string) map[string]interface{} { return map[string]interface{}{ "Shops": shops, "CityName": cityName, "RegionName": regionName, } }
Custom functions are registered using Template.Funcs(). Then, we modify the template to call the Wrap() function:
{{define "data"}} City: {{.CityName}}, Region: {{.RegionName}}, Shops: {{.Shops}} {{end}} {{- range . -}} {{$city:=.Name}} {{- range .Regions -}} {{$region:=.Name}} {{- template "data" (Wrap .Shops $city $region) -}} {{end}} {{- end}}
Finally, a sample code demonstrating these concepts:
t := template.Must(template.New("cities.gohtml").Funcs(template.FuncMap{ "Wrap": Wrap, }).Parse(src)) CityWithSomeData = [...cities] if err := t.ExecuteTemplate(os.Stdout, "cities.gohtml", CityWithSomeData); err != nil { panic(err) }
This approach allows the efficient passing of multiple values from one template to another in Go.
The above is the detailed content of How to Efficiently Pass Multiple Values Between Go Templates?. For more information, please follow other related articles on the PHP Chinese website!