Passing Data Between Templates
In Go's templating system, it can be necessary to pass data between multiple templates, particularly when including one template within another. The question arises, "How can I pass data as arguments to an included template and access it within that template?"
To achieve this, you can utilize a custom function that merges the arguments into a single slice value. By registering this function, it can be used within the template invocation. The following code demonstrates how this is done:
package main
import (
"fmt"
"html/template"
)
func main() {
t, err := template.New("t").Funcs(template.FuncMap{
"args": func(vs ...interface{}) []interface{} { return vs },
}).Parse("{{ template \"image_row\" args . 5 }}")
if err != nil {
fmt.Println(err)
return
}
err = t.Execute(template.Must(template.ParseFiles("index.html", "image_row.html")), nil)
if err != nil {
fmt.Println(err)
return
}
}
// index.html
{{ template "image_row" . | 5 }}
// image_row.html
{{ define "image_row" }}
To stuff here {{index . 0}} {{index . 1}}
{{ end }}
Within the image_row template, the arguments can be accessed using the built-in index function. For example, {{index . 0}} would access the first argument (index 0) passed from the index.html template, in this case the number 5.
This solution provides a versatile way to pass and access data between multiple templates, enabling custom functionality and efficient code reuse.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3