douhuireng4407 2017-01-19 21:11
浏览 78
已采纳

开始-如何使用Pongo2将模板渲染到临时字节缓冲区?

I am trying to send HTML emails using Golang, but instead of using the native Golang html/template package I am trying to do it with Pongo2.

In this question: Is it possible to create email templates with CSS in Google App Engine Go?

The user is providing this example, which is using the html/template

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)

What I am trying to do

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

The problem here is that pongo2.Execute() only allows to enter the context data and not the buff.

My end goal is to be able to write my templates using Pongo2, and I can render the HTML in a way where I can also use it for sending my emails.

My question is what I am doing it wrong? It's possible what I am trying to achieve? If I can find a way to render that HTML into a buff, I can use it later as part buff.String(), which will allow me to enter it in HTML body.

  • 写回答

1条回答 默认 最新

  • duanna5749 2017-01-19 23:32
    关注

    Use ExecuteWriterUnbuffered instead of Execute:

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

    Not sure what w is doing in your example. If it's another Writer that you'd like to write too, you can use an io.MultiWriter.

    // writes to w2 will go to both buff and w
    w2 := io.MultiWriter(&buff, w)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型