转到:没有名称的模板

Is there a way to create a template.Template from a string without giving it a name? Looking at the docs, it seems like the New(name string) is the only way to parse a template string. I wrote a helper function which generates a unique name using an iterator.

var seq chan int

func init() {
    seq = make(chan int)
    go func() {
        for i := 0; true; i++ {
            seq <- i
        }
    }()
}

func TemplateToString(tmplStr string, data interface{}) (string, error) {
    name := fmt.Sprintf("template-%d", <-seq)
    tmpl, err := template.New(name).Parse(tmplStr)
    if err != nil {
        return "", err
    }
    buffer := bytes.Buffer{}
    err = tmpl.Execute(&buffer, data)
    return buffer.String(), err
}

playground

This works, but I would prefer a cleaner approach if it's possible.

You can use "" as the name for your immediate template.