Home > Backend Development > Golang > How to Capture Go Template Output in a Variable Instead of STDOUT?

How to Capture Go Template Output in a Variable Instead of STDOUT?

Patricia Arquette
Release: 2024-11-17 19:40:01
Original
360 people have browsed it

How to Capture Go Template Output in a Variable Instead of STDOUT?

How to Output Template Results to a Variable Instead of STDOUT

In Go templates, the Execute() method typically outputs the template to the screen via the os.Stdout io.Writer. However, you may want to assign the template output to a variable instead.

To accomplish this, you can use the bytes.Buffer or strings.Builder types that implement the io.Writer interface. These types provide an in-memory buffer for writing the template output.

Using bytes.Buffer

var tpl bytes.Buffer
if err := t.Execute(&tpl, data); err != nil {
    return err
}

result := tpl.String()
Copy after login

Using strings.Builder

builder := &strings.Builder{}
if err := t.Execute(builder, data); err != nil {
    return err
}
result := builder.String()
Copy after login

In both cases, the Execute() method writes the template output to the buffer, and you can retrieve the output as a string using the String() method.

The above is the detailed content of How to Capture Go Template Output in a Variable Instead of STDOUT?. 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