Home > Article > Backend Development > How Can I Capture Go Template Output into a Variable Instead of Printing to STDOUT?
Reassigning Template Output to a Variable
In Go, templates provide a convenient way to generate custom output. By default, the output is printed to the standard output (STDOUT) using t.Execute(os.Stdout, xxx). However, there may be instances when you prefer to assign the output to a variable instead.
To accomplish this, it's crucial to remember that t.Execute expects an input that implements the io.Writer interface. One suitable option is to utilize a buffer, such as a bytes.Buffer or strings.Builder.
Using a bytes.Buffer:
var tpl bytes.Buffer if err := t.Execute(&tpl, data); err != nil { return err } result := tpl.String()
This code creates a bytes.Buffer and passes its address to t.Execute. If the template execution is successful, the output is stored in the buffer, which can then be retrieved as a string using tpl.String().
Using a strings.Builder:
builder := &strings.Builder{} if err := t.Execute(builder, data); err != nil { return err } result := builder.String()
The strings.Builder provides a more specialized alternative. Similar to the previous approach, the builder is passed to t.Execute as an io.Writer, and the output is collected in the builder. The builder.String() method can then be used to retrieve the output as a string.
The above is the detailed content of How Can I Capture Go Template Output into a Variable Instead of Printing to STDOUT?. For more information, please follow other related articles on the PHP Chinese website!