猿问

将执行文本/模板模板的结果分配到变量中

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)

如何将模板执行的结果保存在 golang 变量中,而不是写入 。os.Stdout


慕森卡
浏览 70回答 1
1回答

心有法竹

正如您在此处看到的 https://golang.org/pkg/text/template/#Template.Execute,execute方法中有一个arg,因此您可以传递任何io.Writerio.Writer我希望这会有所帮助。https://play.golang.org/p/kXRQ7G3uO20package mainimport (    "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)}
随时随地看视频慕课网APP

相关分类

Go
我要回答