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

How to Capture Golang Template Output into a Variable?

Susan Sarandon
Release: 2024-12-19 03:32:21
Original
132 people have browsed it

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
}
Copy after login
  1. Register this function with the template:
t := template.Must(template.New("").Funcs(template.FuncMap{
    "execTempl": execTempl,
}).Parse(tmpl))
Copy after login
  1. Use the registered function to capture the output of a named template:
{{$var := execTempl "my-template"}}
Copy after login

Example Template:

const tmpl = `{{define "my-template"}}my-template content{{end}}
See result:
{{$var := execTempl "my-template"}}
{{$var}}
`
Copy after login

Output:

See result:

my-template content
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template