dtny30176 2016-05-09 20:32
浏览 277
已采纳

go不能在模板Execute的参数中将输出(字符串类型)用作io.Writer类型

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)

  • 写回答

1条回答 默认 最新

  • dtv7174 2016-05-09 20:36
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?