I need to use the *template.Execute method but I want the result as a string or byte[] so that I can pass it to another *template.Execute but the method writes its results to a writer. Is there a way to create a writer that will write to a variable I define?
Go supports two styles of string literals, the double-quote style (or interpreted literals) and the back-quote style (or raw string literals). The zero values of string types are blank strings, which can be represented with "" or `` in literal. Strings can be concatenated with + and += operators.
The io.Writer interface is used by many packages in the Go standard library and it represents the ability to write a byte slice into a stream of data. More generically allows you to write data into something that implements the io.Writer interface.
Builder is used to efficiently append strings using write methods. It offers a subset of the bytes. Buffer methods that allows it to safely avoid extra copying when converting a builder to a string.
Use an instance of bytes.Buffer
, which implements io.Writer
:
var buff bytes.Buffer
if err := tpl.Execute(&buff, data); err != nil {
panic(err)
}
You can then get a string
result using buff.String()
, or a []byte
result using buff.Bytes()
.
You can also use strings.Builder
for this purpose:
package main
import (
"html/template"
"strings"
)
func main() {
t, e := template.New("date").Parse("<p>{{ .month }} - {{ .day }}</p>")
if e != nil {
panic(e)
}
b := new(strings.Builder)
t.Execute(b, map[string]int{"month": 12, "day": 31})
println(b.String())
}
https://golang.org/pkg/strings#Builder
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With