Skip to content

Commit

Permalink
fix(templating): simplify template API and make it optional
Browse files Browse the repository at this point in the history
  • Loading branch information
piksel committed Jun 23, 2019
1 parent 5abddb0 commit 92a6d86
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 14 deletions.
1 change: 0 additions & 1 deletion pkg/services/standard/standard.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package standard
// Standard implements the Logger and Templater parts of the Service interface
type Standard struct {
Logger
Templater
Initializer
QueuedSender
}
36 changes: 23 additions & 13 deletions pkg/services/standard/standard_templater.go
Original file line number Diff line number Diff line change
@@ -1,26 +1,36 @@
package standard

import (
"strings"
"io/ioutil"
"text/template"
)

// Templater is the standard implementation of ApplyTemplate using the "text/template" library
type Templater struct {}
type Templater struct {
templates map[string]*template.Template
}

// ApplyTemplate applies the params to the input template and returns the result
func (templater *Templater) ApplyTemplate (tpl string, params *map[string]string) (string, error) {
engine, err := template.New("").Parse(tpl);
// GetTemplate attempts to retrieve the template identified with id
func (templater *Templater) GetTemplate (id string) (template *template.Template, found bool) {
tpl, found := templater.templates[id]
return tpl, found
}

// SetTemplateString creates a new template from the body and assigning it the id
func (templater *Templater) SetTemplateString (id string, body string) error {
tpl, err := template.New("").Parse(body)
if err != nil {
return "", err
return err
}
templater.templates[id] = tpl
return nil
}

writer := strings.Builder{}

if err := engine.Execute(&writer, params); err != nil {
return "", err
// SetTemplateFile creates a new template from the file and assigning it the id
func (templater *Templater) SetTemplateFile (id string, file string) error {
bytes, err := ioutil.ReadFile(file)
if err != nil {
return err
}

return writer.String(), err

return templater.SetTemplateString(id, string(bytes))
}

0 comments on commit 92a6d86

Please sign in to comment.