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

iro*_*rom 2 go

在'go'到os.Stdout中执行模板(在我的情况下是'tmplhtml')很容易但是如何将它写入字符串'output'以便稍后我可以使用邮件发送html "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"
Run Code Online (Sandbox Code Playgroud)

构建错误读取'不能使用输出(类型字符串)作为类型io.Writer在t的参数中.Execute:string不实现io.Writer(缺少Write方法)'我可以实现Writer方法但它应该返回整数Write( p [] byte)(n int,错误错误)

mil*_*onb 5

您需要按如下方式写入缓冲区,因为这会实现接口io.Writer.它基本上缺少一个Write方法,你可以构建自己的方法,但缓冲区更直接:

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

  • 缓冲区很容易转换为字符串,我认为它只是`buf.String()`文档是https://golang.org/pkg/bytes/#Buffer.String (5认同)