-
Notifications
You must be signed in to change notification settings - Fork 64
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(templating): simplify template API and make it optional
- Loading branch information
Showing
2 changed files
with
23 additions
and
14 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
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)) | ||
} |