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

How to save a rendered template instead of printing into os.Stdout?

我是 Go 新手。我一直在搜索文档。在下面的游乐场代码中,它正在屏幕上渲染和打印它。我希望将呈现的文本存储在字符串中,以便我可以从函数中 return 它。

package main

import (
    "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

怎么做?

只需将其渲染到内存缓冲区中,例如 bytes.Buffer (or strings.Builder added in Go 1.10) whose content you can obtain as a string by calling its Bytes.String() (or Builder.String()) 方法:

buf := &bytes.Buffer{}
if err := t.Execute(buf, p); err != nil {
    panic(err)
}

s := buf.String()
fmt.Println(s)

这将再次打印(在 Go Playground 上尝试):

hello Mary!

但这次是 s 字符串变量的值。

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

buf := &strings.Builder{}

Go Playground 上试试这个。

参见相关问题:Format a Go string without printing?