在“go”到os.Stdout 中執行模板(在我的情況下為“tmplhtml”)很容易,但如何將其寫入字符串“輸出”,以便我以后可以使用"gopkg.in/gomail.v2"?發送郵件中的 html ?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"構建錯誤讀取“不能在 t.Execute 的參數中使用輸出(字符串類型)作為 io.Writer 類型:字符串沒有實現 io.Writer(缺少寫入方法)”我可以實現 Writer 方法,但它應該返回整數寫入( p []byte) (n int, err 錯誤)
2 回答

吃雞游戲
TA貢獻1829條經驗 獲得超7個贊
您需要按如下方式寫入緩沖區,因為它實現了接口io.Writer。它基本上缺少一個 Write 方法,您可以構建自己的方法,但緩沖區更直接:
buf := new(bytes.Buffer)
t := template.Must(template.New("html table").Parse(tmplhtml))
err = t.Execute(buf, Files)

翻過高山走不出你
TA貢獻1875條經驗 獲得超3個贊
您還可以使用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())
}
- 2 回答
- 0 關注
- 209 瀏覽
添加回答
舉報
0/150
提交
取消