Skip to content

Commit

Permalink
fix: support rendering nil templates
Browse files Browse the repository at this point in the history
  • Loading branch information
twelvelabs committed Jun 10, 2023
1 parent c7c534b commit af45bc7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
3 changes: 3 additions & 0 deletions render/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ func String(s string, data any) (string, error) {
}

func execute(t *template.Template, data any) (string, error) {
if t == nil {
return "", nil
}
buf := bytes.Buffer{}
err := t.Execute(&buf, data)
if err != nil {
Expand Down
12 changes: 9 additions & 3 deletions render/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,20 @@ func TestTemplate_UnmarshalText(t *testing.T) {
func TestTemplate_UnmarshalFromYAML(t *testing.T) {
s := `greeting: "Hello, {{ .Name }}"`
mapping := struct {
Greeting *Template `yaml:"greeting"`
Greeting Template `yaml:"greeting"`
Missing Template `yaml:"missing"`
}{}
err := yaml.Unmarshal([]byte(s), &mapping)
assert.NoError(t, err)

rendered, err := mapping.Greeting.Render(map[string]any{
data := map[string]any{
"Name": "World",
})
}
rendered, err := mapping.Greeting.Render(data)
assert.NoError(t, err)
assert.Equal(t, "Hello, World", rendered)

rendered, err = mapping.Missing.Render(data)
assert.NoError(t, err)
assert.Equal(t, "", rendered)
}

0 comments on commit af45bc7

Please sign in to comment.