1

I am new to Go. I have been searching Documentation. In the following playground code, it is rendering and printing it on the screen. I want the rendered text to be stored in string so that I can return it from a function.

package main

import (
    "os"
    "text/template"
)

type Person struct {
    Name string //exported field since it begins with a capital letter
}



func main() {
    t := template.New("sammple") //create a new template with some name
    t, _ = t.Parse("hello {{.Name}}!") //parse some content and generate a template, which is an internal representation

    p := Person{Name:"Mary"} //define an instance with required field
    t.Execute(os.Stdout, p) //merge template ‘t’ with content of ‘p’
}

https://play.golang.org/p/-qIGNSfJwEX

How to do it ?

icza
  • 389,944
  • 63
  • 907
  • 827
Mayukh Sarkar
  • 2,289
  • 1
  • 14
  • 38

1 Answers1

3

Simply render it into an in-memory buffer such as bytes.Buffer (or strings.Builder added in Go 1.10) whose content you can obtain as a string by calling its Bytes.String() (or Builder.String()) method:

buf := &bytes.Buffer{}
if err := t.Execute(buf, p); err != nil {
    panic(err)
}

s := buf.String()
fmt.Println(s)

This will again print (try it on the Go Playground):

hello Mary!

But this time this is the value of the s string variable.

Using strings.Builder(), you only need to change this line:

buf := &strings.Builder{}

Try this one on the Go Playground.

See related question: Format a Go string without printing?

icza
  • 389,944
  • 63
  • 907
  • 827