Capturing Template Output in Go
Within a Go template, capturing the output of a sub-template or assigning it to a variable directly is not supported by default. This can be achieved, however, by registering a custom function and using a bytes buffer to receive the template's result.
Custom Function Registration
To capture template output, register a function with Template.Funcs() that takes the template name as an argument and returns the template's output as a string:
func execTempl(name string) (string, error) { buf := &bytes.Buffer{} err := t.ExecuteTemplate(buf, name, nil) return buf.String(), err }
Template Execution and Result Capture
Execute the sub-template named 'my-template' using Template.ExecuteTemplate() and assign it to a variable:
{{$var := execTempl "my-template"}}
Output Retrieval
Retrieve the captured output and use it as needed:
See result: {{$var}}
Complete Example
var t *template.Template func main() { t = template.Must(template.New("").Funcs(template.FuncMap{ "execTempl": execTempl, }).Parse(tmpl)) if err := t.Execute(os.Stdout, nil); err != nil { panic(err) } } const tmpl = ` {{define "my-template"}}my-template content{{end}} See result: {{$var := execTempl "my-template"}} {{$var}} `
Output:
See result: my-template content
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