My City
struct is like this:
type City struct {
ID int
Name string
Regions []Region
}
And Region
struct is:
type Region struct {
ID int
Name string
Shops []Destination
Masters []Master
EducationCenters []Destination
}
In main I try to do this:
tpl.ExecuteTemplate(resWriter,"cities.gohtml",CityWithSomeData)
Is it possible to do something like this inside template?
{{range .}}
{{$city:=.Name}}
{{range .Regions}}
{{$region:=.Name}}
{{template "data" .Shops $city $region}}
{{end}}
{{end}}
Quoting from the doc of
text/template
, the syntax of the{{template}}
action:This means you may pass one optional data to the template execution, not more. If you want to pass multiple values, you have to wrap them into some single value you pass. For details, see How to pass multiple data to Go template?
So we should wrap those data into a struct or a map. But we can't write Go code in a template. What we may do is register a function to which we pass these data, and the function may do the "packing" and return a single value which now we can pass to the
{{template}}
action.Here's an example wrapper which simply packs these into a map:
Custom functions can be registered using the
Template.Funcs()
method, and don't forget you have to do this before you parse the template text.Here's a modified template which calls this
Wrap()
function to produce a single value:And here's a runnable example showing these in action:
Output (try it on the Go Playground):
I guess
CityWithSomeData
is a slice, if so have a try like that:then, in your template: