首页 > 解决方案 > 将执行文本/模板模板的结果分配给变量

问题描述

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 变量中,而不是写入到?

标签: gogo-templates

解决方案


正如您在这里看到的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)
}


推荐阅读