【问题标题】:go cannot use output (type string) as type io.Writer in argument to template Executego 不能在模板 Execute 的参数中使用输出(类型字符串)作为类型 io.Writer
【发布时间】:2016-09-04 15:06:21
【问题描述】:

在“go”到 os.Stdout 中执行模板(在我的情况下为“tmplhtml”)很容易,但是如何将其写入字符串“输出”以便我以后可以发送 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"

构建错误读取 'cannot use output (type string) as type io.Writer in argument to t.Execute: string does not implement io.Writer (missing Write method)' 我可以实现 Writer方法,但它应该返回整数 Write(p []byte) (n int, err error)

【问题讨论】:

    标签: go


    【解决方案1】:

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

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

    【讨论】:

    • 不能在 m.SetBody 的参数中使用 buf (type *bytes.Buffer) 作为类型字符串
    • 缓冲区很容易转换为字符串,我认为它只是buf.String() 文档是golang.org/pkg/bytes/#Buffer.String
    【解决方案2】:

    你也可以使用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())
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 2011-07-29
      • 2021-10-21
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多