Home >Backend Development >Golang >How to Pass Multiple Values Between Go Templates?

How to Pass Multiple Values Between Go Templates?

Linda Hamilton
Linda HamiltonOriginal
2024-12-04 16:33:10357browse

How to Pass Multiple Values Between Go Templates?

Passing Multiple Values Between Go Templates

When working with Go templates, it can be necessary to pass multiple values between templates. However, the text/template package's {{template}} action only supports passing a single optional data value. This raises the question of how to effectively transfer multiple data elements. One approach is to consolidate the data into a single value. Go provides two options: wrapping the data into a struct or utilizing a map.

Wrapping Into a Struct

One method is to create a struct that encapsulates the data you wish to transfer. This struct can then be passed to the template and used with the dot notation to access the individual data elements within the template. Here's an example:

type DataWrapper struct {
    Shops      []Destination
    CityName   string
    RegionName string
}

Wrapping Into a Map

If using a struct is inconvenient, you can also wrap the data into a simple map. The map keys will represent the data element names, and the map values will be the actual data values. Here's an example:

func Wrap(shops []Destination, cityName, regionName string) map[string]interface{} {
    return map[string]interface{}{
        "Shops":      shops,
        "CityName":   cityName,
        "RegionName": regionName,
    }
}

Integrating With Custom Functions

Once you have wrapped your data into a struct or map, you can use a custom function to pass this data to the template. Custom functions can be registered with the Template.Funcs() method, and you must do this before parsing the template text. Here's an example of using a custom function for passing data:

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}}`

Conclusion

By structuring your data into a single value and utilizing custom functions, you can effectively pass multiple values between Go templates. This enables you to efficiently share complex data structures between different parts of your templates, enhancing the flexibility and maintainability of your Go web applications.

The above is the detailed content of How to Pass Multiple Values Between Go Templates?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn