irom
irom

Reputation: 3606

go cannot use output (type string) as type io.Writer in argument to template Execute

It's easy to execute template ('tmplhtml' in my case) in 'go' to os.Stdout but how to write it to a string 'output' so I can later i.e. send html in mail using "gopkg.in/gomail.v2" ?

var output string
    t := template.Must(template.New("html table").Parse(tmplhtml))
    err = t.Execute(output, Files)
m.SetBody("text/html", output) //"gopkg.in/gomail.v2"

Build error reads 'cannot use output (type string) as type io.Writer in argument to t.Execute: string does not implement io.Writer (missing Write method)' I can implement Writer method but it is supposed to return integer Write(p []byte) (n int, err error)

Upvotes: 3

Views: 6467

Answers (2)

Zombo
Zombo

Reputation: 1

You can also use strings.Builder:

package main

import (
   "strings"
   "text/template"
)

func main() {
   t, err := new(template.Template).Parse("hello {{.}}")
   if err != nil {
      panic(err)
   }
   b := new(strings.Builder)
   t.Execute(b, "world")
   println(b.String())
}

Upvotes: 1

miltonb
miltonb

Reputation: 7385

You need to write to a buffer as follows as this implements the interface io.Writer. Its basically missing a Write method, which you could build your own, but a buffer is more straight forward:

buf := new(bytes.Buffer)
t := template.Must(template.New("html table").Parse(tmplhtml))
err = t.Execute(buf, Files)

Upvotes: 6

Related Questions