go - 将执行文本/模板模板的结果分配给变量
问题描述
type Inventory struct {
Material string
Count uint
}
sweaters := Inventory{"wool", 17}
tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
err = tmpl.Execute(os.Stdout, sweaters)
os.Stdout
我怎样才能将模板执行的结果保存在 golang 变量中,而不是写入到?
解决方案
正如您在这里看到的https://golang.org/pkg/text/template/#Template.Executeio.Writer
,执行方法中有一个arg,因此您可以传递任何io.Writer
我希望这将有所帮助。https://play.golang.org/p/kXRQ7G3uO20
package main
import (
"fmt"
"bytes"
"text/template"
)
type Inventory struct {
Material string
Count uint
}
func main() {
var buf bytes.Buffer
sweaters := Inventory{"wool", 17}
tmpl, _ := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
_ = tmpl.Execute(&buf, sweaters)
s := buf.String()
fmt.Println(s)
}
推荐阅读
- c - GCC编译的二进制文件中的冗余寄存器值?
- c# - 登录时 LoggedInTemplate 不显示(改为显示 AnonymousTemplate)
- vagrant - 在 windows server 2016 标准中运行 Vagrant
- python - 在Python中将算术序列转换为切片
- linux - 关于信号处理程序中的非信号安全系统调用
- python - 使用多重继承时 PyQt5 中的 MRO 错误
- python - 无法将 pytorch 安装到我的 anaconda 虚拟环境
- c - 当 Source 和 Include 在子目录中时如何编写 Makefile
- javascript - 使用 jest 测试没有回调的异步函数
- android - Google Pay android生产模式的问题