【问题标题】:Go - How to render the template to a temporary byte buffer using Pongo2?Go - 如何使用 Pongo2 将模板渲染到临时字节缓冲区?
【发布时间】:2018-05-25 16:02:52
【问题描述】:

我正在尝试使用 Golang 发送 HTML 电子邮件,但我尝试使用 Pongo2 而不是使用本机 Golang html/template 包。

在这个问题中:Is it possible to create email templates with CSS in Google App Engine Go?

用户正在提供这个示例,它使用的是 html/模板

var tmpl = template.Must(template.ParseFiles("templates/email.html"))

buff := new(bytes.Buffer)
if err = tmpl.Execute(buff, struct{ Name string }{"Juliet"}); err != nil {
    panic(err.Error())
}
msg := &mail.Message{
    Sender:   "romeo@montague.com",
    To:       []string{"Juliet <juliet@capulet.org>"},
    Subject:  "See you tonight",
    Body:     "...you put here the non-HTML part...",
    HTMLBody: buff.String(),
}
c := appengine.NewContext(r)
if err := mail.Send(c, msg); err != nil {
    c.Errorf("Alas, my user, the email failed to sendeth: %v", err)

我想做什么

var tmpl = pongo2.Must(pongo2.FromFile("template.html"))
buff := new(bytes.Buffer)
tmpl.Execute(buff, pongo2.Context{"data": "best-data"}, w)

这里的问题是pongo2.Execute()只允许输入上下文数据,不能输入buff。

我的最终目标是能够使用Pongo2 编写我的模板,并且我可以以一种我也可以使用它来发送我的电子邮件的方式呈现 HTML。

我的问题是我做错了什么?我想要达到的目标可能是什么?如果我能找到一种方法将该 HTML 呈现为 buff,我可以稍后将其用作 buff.String() 的一部分,这样我就可以在 HTML 正文中输入它。

【问题讨论】:

    标签: go html-email


    【解决方案1】:

    使用ExecuteWriterUnbuffered 代替Execute

    tmpl.ExecuteWriterUnbuffered(pongo2.Context{"data": "best-data"}, &buff)
    

    不确定w 在您的示例中做了什么。如果您也想写另一个Writer,可以使用io.MultiWriter

    // writes to w2 will go to both buff and w
    w2 := io.MultiWriter(&buff, w)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多