2
type Inventory struct {
    Material string
    Count    uint
}

sweaters := Inventory{"wool", 17}
tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
err = tmpl.Execute(os.Stdout, sweaters)

Instead of writing to os.Stdout, how can I save the result of the template execution in a golang variable?

Victor Cui
  • 1,393
  • 2
  • 15
  • 35

1 Answers1

4

as you may see here https://golang.org/pkg/text/template/#Template.Execute, there is an io.Writer arg in the execute method, so you may pass any io.Writer

i hope this will help. https://play.golang.org/p/kXRQ7G3uO20

package main

import (
    "fmt"
    "bytes"
    "text/template"
)

type Inventory struct {
    Material string
    Count    uint
}


func main() {
    var buf bytes.Buffer
    sweaters := Inventory{"wool", 17}
    tmpl, _ := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
    _ = tmpl.Execute(&buf, sweaters)
    
    s := buf.String()
    fmt.Println(s)
}

bobra
  • 615
  • 3
  • 18