Присвойте результат выполнения шаблона текста / шаблона переменной

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?


person Victor Cui    schedule 12.04.2021    source источник


Ответы (1)


как вы можете видеть здесь https://golang.org/pkg/text/template/#Template.Execute, в методе execute есть io.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)
}

person bobra    schedule 12.04.2021