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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么