Home >Backend Development >Golang >How to Capture Golang Template Output into a Variable?

How to Capture Golang Template Output into a Variable?

Susan Sarandon
Susan SarandonOriginal
2024-12-19 03:32:21136browse

How to Capture Golang Template Output into a Variable?

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:

  1. Register a function that executes a named template and stores the result in a buffer:
func execTempl(name string) (string, error) {
    buf := &bytes.Buffer{}
    err := t.ExecuteTemplate(buf, name, nil)
    return buf.String(), err
}
  1. Register this function with the template:
t := template.Must(template.New("").Funcs(template.FuncMap{
    "execTempl": execTempl,
}).Parse(tmpl))
  1. Use the registered function to capture the output of a named template:
{{$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!

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