Last Updated: January 29, 2020
· septiaji

Simply output go html template execution to strings

Instead of executing html template into io.Writer interface like *http.ResponseWriter, sometimes we just only want strings as output from go lang html template execution.

To achieve this we can simply use any types that implement io.Writer interface. For this strings case, we can use a buffer's pointer to store html template execution result then parse them to string.

t := template.New("action")

var err error
t, err = t.ParseFiles("path/to/action.html")
if err != nil {
    return err

key := "some strings"

data := struct{
    Key string
    Key: key

var tpl bytes.Buffer
if err := t.Execute(&tpl, data); err != nil {
    return err

result := tpl.String()

happy holiday!