首页 > 解决方案 > 如何保存渲染的模板而不是打印到 os.Stdout?

问题描述

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

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

怎么做 ?

标签: stringtemplatesgogo-templates

解决方案


只需将其渲染到内存缓冲区中,例如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上试试这个。

请参阅相关问题:格式化 Go 字符串而不打印?


推荐阅读