Capturing Golang Template Output into a Variable
Within a Golang template, attempting to capture the output of another template directly into a variable can result in an error. To achieve this functionality, a custom function must be registered to capture the output.
Solution:
func execTempl(name string) (string, error) { buf := &bytes.Buffer{} err := t.ExecuteTemplate(buf, name, nil) return buf.String(), err }
t := template.Must(template.New("").Funcs(template.FuncMap{ "execTempl": execTempl, }).Parse(tmpl))
{{$var := execTempl "my-template"}}
Example Template:
const tmpl = `{{define "my-template"}}my-template content{{end}} See result: {{$var := execTempl "my-template"}} {{$var}} `
Output:
See result: my-template content
This approach allows you to execute a named template and store its output in a template variable. You can then use this variable to pass to other functions or include in the template output.
The above is the detailed content of How to Capture Golang Template Output into a Variable?. For more information, please follow other related articles on the PHP Chinese website!