我是新來的。我一直在搜索文檔。在下面的游樂場代碼中,它正在屏幕上渲染和打印它。我希望將呈現的文本存儲在字符串中,以便我可以從函數中返回它。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)
hello Mary!
但這次是s
字符串變量的值。
使用strings.Builder()
,你只需要改變這一行:
buf := &strings.Builder{}
在Go Playground試試這個。
- 1 回答
- 0 關注
- 78 瀏覽
添加回答
舉報
0/150
提交
取消