Go - 如何使用 Pongo2 将模板渲染到临时字节缓冲区?
Go - How to render the template to a temporary byte buffer using Pongo2?
我正在尝试使用 Golang 发送 HTML 电子邮件,但我尝试使用 Pongo2 而不是使用原生 Golang html/template 包。
本题中:Is it possible to create email templates with CSS in Google App Engine Go?
用户提供了这个例子,它使用了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)
我想做什么
var tmpl = pongo2.Must(pongo2.FromFile("template.html"))
buff := new(bytes.Buffer)
tmpl.Execute(buff, pongo2.Context{"data": "best-data"}, w)
这里的问题是 pongo2.Execute() 只允许输入上下文数据而不是增益。
我的最终目标是能够使用 Pongo2 编写我的模板,并且我可以呈现 HTML 的方式,我也可以用它来发送我的电子邮件。
我的问题是我做错了什么?这可能是我想要达到的目标吗?如果我能找到一种方法将 HTML 渲染成一个 buff,我可以稍后将它用作 buff.String()
的一部分,这将允许我将它输入 HTML body.
使用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)
我正在尝试使用 Golang 发送 HTML 电子邮件,但我尝试使用 Pongo2 而不是使用原生 Golang html/template 包。
本题中:Is it possible to create email templates with CSS in Google App Engine Go?
用户提供了这个例子,它使用了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)
我想做什么
var tmpl = pongo2.Must(pongo2.FromFile("template.html"))
buff := new(bytes.Buffer)
tmpl.Execute(buff, pongo2.Context{"data": "best-data"}, w)
这里的问题是 pongo2.Execute() 只允许输入上下文数据而不是增益。
我的最终目标是能够使用 Pongo2 编写我的模板,并且我可以呈现 HTML 的方式,我也可以用它来发送我的电子邮件。
我的问题是我做错了什么?这可能是我想要达到的目标吗?如果我能找到一种方法将 HTML 渲染成一个 buff,我可以稍后将它用作 buff.String()
的一部分,这将允许我将它输入 HTML body.
使用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)