string - 如何保存渲染的模板而不是打印到 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
怎么做 ?
解决方案
只需将其渲染到内存缓冲区中,例如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 字符串而不打印?
推荐阅读
- android-studio - IntelliJ - 是否有自动向构造函数添加额外参数的选项?
- ruby-on-rails - API 模式下的 Sidekiq + Rails 6.0.0 : WARN -- : 攻击被 Rack::Protection::AuthenticityToken 阻止
- python - 使用python将json文件导入mongoDB
- azure-devops - Azure DevOps 中的聊天功能
- odoo - 为什么这个域没有给我结果?
- python - CP-SAT 中的性能问题
- sql - 从日期范围计算特定日期的分钟数
- google-cloud-platform - 如何使用 Airflow 将 BigQuery 分区导出到 GCS
- java - 从 excel 文件中读取并加载到 SOAP UI 请求中
- javascript - 可以使用 Workbox 缓存策略在页面请求图像之前预加载图像吗?