Get output of template to a variable instead to STDOUT

Viewed 433

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?

1 Answers

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