Retrieving Template Output in a Variable
In Go's templating system, the Execute method outputs the rendered template to the provided io.Writer argument. By default, this is typically directed to the standard output (e.g., os.Stdout). However, in certain scenarios, it may be desirable to capture the template output in a variable for further manipulation.
To achieve this, you can leverage two alternative approaches:
Using bytes.Buffer:
var tpl bytes.Buffer if err := t.Execute(&tpl, data); err != nil { return err } result := tpl.String()
bytes.Buffer implements the io.Writer interface, allowing you to use it as a target for the template output. After the Execute call, you can retrieve the rendered content as a string using the String method.
Using strings.Builder:
builder := &strings.Builder{} if err := t.Execute(builder, data); err != nil { return err } result := builder.String()
strings.Builder provides a more specialized way of collecting strings. It offers methods tailored for efficient string concatenation, making it particularly suitable for capturing template output in certain situations.
The above is the detailed content of How Can I Capture Go Template Output into a Variable?. For more information, please follow other related articles on the PHP Chinese website!