3

I am using templates with Golang and at some point I use this code:

t.Execute(os.Stdout, xxx);

This code above outputs the template to the screen (because of os.Stdout) but I would like it to be assigned to a variable instead, something like

var temp string;
e := t.Execute(temp, xxx);

But of course, this code does not work. So how can I do this?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Samul
  • 1,824
  • 5
  • 22
  • 47
  • Try [`strings.Builder`](https://golang.org/pkg/strings/#Builder). – mkopriva Oct 10 '20 at 19:00
  • 2
    As presented in this answer: [Format a Go string without printing?](https://stackoverflow.com/questions/11123865/format-a-go-string-without-printing/31742265#31742265) – icza Oct 10 '20 at 20:01

1 Answers1

5

t.Execute expects a type that implements io.Writer interface. One option is to use Buffer:

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

result := tpl.String()

Another, more specialized alternative is strings.Builder, mentioned in the comments:

builder := &strings.Builder{}
if err := t.Execute(builder, data); err != nil {
    return err
}
result := builder.String()
raina77ow
  • 103,633
  • 15
  • 192
  • 229