本文介绍了go不能在模板Execute的参数中使用输出(字符串类型)作为io.Writer类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很容易在" os.Stdout "中执行模板(在我的情况下为"tmplhtml"),但是如何将其写入字符串输出",这样我以后就可以发送html了.使用"gopkg.in/gomail.v2" 发送邮件?

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"

构建错误读取无法在t的参数中将输出(字符串类型)用作io.Writer类型.执行:字符串未实现io.Writer(缺少Write方法)" 我可以实现Writer方法,但应该返回整数 Write(p [] byte)(n int,错误错误)

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)

推荐答案

您需要按照以下说明写入缓冲区,因为这实现了 io.Writer 接口.它基本上缺少Write方法,您可以构建自己的Write方法,但是缓冲区更直接:

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)

这篇关于go不能在模板Execute的参数中使用输出(字符串类型)作为io.Writer类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 10:35