Home  >  Article  >  Backend Development  >  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
Patricia ArquetteOriginal
2024-11-17 19:40:01275browse

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()

Using strings.Builder

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

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!

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