Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott
Created April 2, 2021 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdwhatcott/69ec846b248ee1a6593ba385285cf7ba to your computer and use it in GitHub Desktop.
Save mdwhatcott/69ec846b248ee1a6593ba385285cf7ba to your computer and use it in GitHub Desktop.
fmt.Sprintf -> template.Execute
package templates
import (
"bytes"
"fmt"
"io"
"text/template"
)
func ParseAndExecute(format string, args ...interface{}) string {
var out bytes.Buffer
executor := NewExecutor(&out)
_ = executor.ParseAndExecute(format, args...)
return out.String()
}
type Executor struct {
writer io.Writer
}
func NewExecutor(writer io.Writer) *Executor {
return &Executor{writer: writer}
}
func (this *Executor) Execute(t *template.Template, args ...interface{}) error {
data := make(map[string]interface{})
for a, arg := range args {
data[fmt.Sprint(a)] = arg
}
return t.Execute(this.writer, data)
}
func (this *Executor) ParseAndExecute(format string, args ...interface{}) error {
t, err := template.New("").Parse(format)
if err != nil {
return err
}
return this.Execute(t, args...)
}
package templates
import (
"bytes"
"testing"
)
func TestExecutor(t *testing.T) {
out := new(bytes.Buffer)
executor := NewExecutor(out)
err := executor.ParseAndExecute(rawTemplate, data)
if err != nil {
t.Error(err)
}
actual := out.String()
if actual != expected {
t.Errorf("\n"+
"Expected: %s\n"+
"Actual: %s",
expected,
actual,
)
}
}
func TestExecute(t *testing.T) {
actual := ParseAndExecute(rawTemplate, data)
if actual != expected {
t.Errorf("\n"+
"Expected: %s\n"+
"Actual: %s",
expected,
actual,
)
}
}
var data = map[string]interface{}{
"FirstName": "Bob",
"LastName": "Johnson",
}
var (
rawTemplate = "Hello, my name is {{.FirstName}} {{.LastName}}."
expected = "Hello, my name is Bob Johnson."
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment