为了账号安全,请及时绑定邮箱和手机立即绑定

如何保存呈现的模板而不是打印到 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条经验 获得超3个赞

只需将其呈现到内存缓冲区中,例如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)

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

hello Mary!

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

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

buf := &strings.Builder{}

在Go Playground试试这个。


查看完整回答
反对 回复 2023-03-21
  • 1 回答
  • 0 关注
  • 50 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信