亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何保存呈現的模板而不是打印到 os.Stdout?

如何保存呈現的模板而不是打印到 os.Stdout?

Go
九州編程 2023-03-21 15:17:37
我是新來的。我一直在搜索文檔。在下面的游樂場代碼中,它正在屏幕上渲染和打印它。我希望將呈現的文本存儲在字符串中,以便我可以從函數中返回它。package mainimport (    "os"    "text/template")type Person struct {    Name string //exported field since it begins with a capital letter}func main() {    t := template.New("sammple") //create a new template with some name    t, _ = t.Parse("hello {{.Name}}!") //parse some content and generate a template, which is an internal representation    p := Person{Name:"Mary"} //define an instance with required field    t.Execute(os.Stdout, p) //merge template ‘t’ with content of ‘p’}https://play.golang.org/p/-qIGNSfJwEX怎么做 ?
查看完整描述

1 回答

?
Helenr

TA貢獻1780條經驗 獲得超4個贊

只需將其呈現到內存緩沖區中,例如bytes.Buffer(或strings.Builder在 Go 1.10 中添加),您可以通過string調用其Bytes.String()(or Builder.String()) 方法獲取其內容:

buf := &bytes.Buffer{}

if err := t.Execute(buf, p); err != nil {

    panic(err)

}


s := buf.String()

fmt.Println(s)

這將再次打?。ㄔ贕o Playground上嘗試):

hello Mary!

但這次是s字符串變量的值。

使用strings.Builder(),你只需要改變這一行:

buf := &strings.Builder{}

在Go Playground試試這個。


查看完整回答
反對 回復 2023-03-21
  • 1 回答
  • 0 關注
  • 78 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號