Created
April 2, 2021 16:56
-
-
Save mdwhatcott/69ec846b248ee1a6593ba385285cf7ba to your computer and use it in GitHub Desktop.
fmt.Sprintf -> template.Execute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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...) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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