summaryrefslogtreecommitdiff
path: root/templates.go
diff options
context:
space:
mode:
authorFelix Hanley <felix@userspace.com.au>2020-02-13 12:16:24 +0000
committerFelix Hanley <felix@userspace.com.au>2020-02-13 12:16:24 +0000
commit2839acfa12d30cff97803d1db688d2f3823ff0cc (patch)
treecc1bf3f0bc1ab822a548bace7568918077292af3 /templates.go
parentf58212f65bbdf6656e4c656de8b352eda2319869 (diff)
downloadtemplates-2839acfa12d30cff97803d1db688d2f3823ff0cc.tar.gz
templates-2839acfa12d30cff97803d1db688d2f3823ff0cc.tar.bz2
Use map over struct for template vars
Diffstat (limited to 'templates.go')
-rw-r--r--templates.go41
1 files changed, 29 insertions, 12 deletions
diff --git a/templates.go b/templates.go
index 9655ead..50afff1 100644
--- a/templates.go
+++ b/templates.go
@@ -39,6 +39,13 @@ func New(opts ...Option) (*Templates, error) {
return out, nil
}
+func Must(t *Templates, err error) *Templates {
+ if err != nil {
+ panic(err)
+ }
+ return t
+}
+
type Option func(*Templates) error
func Base(p string) Option {
@@ -55,6 +62,7 @@ func Extension(e string) Option {
return nil
}
}
+
func Package(p string) Option {
return func(t *Templates) error {
t.pkg = p
@@ -100,19 +108,20 @@ func (t *Templates) WriteTo(w io.Writer) (int64, error) {
data[k] = base64.StdEncoding.EncodeToString(b)
}
var buf bytes.Buffer
- if err := tmpl.Execute(&buf, struct {
- Package string
- Base string
- FName string
- Extension string
- Templates map[string]string
- }{t.pkg, t.base, t.fName, t.extension, data}); err != nil {
+ vars := map[string]interface{}{
+ "package": t.pkg,
+ "base": t.base,
+ "function": t.fName,
+ "extension": t.extension,
+ "templates": data,
+ }
+ if err := tmpl.Execute(&buf, vars); err != nil {
return 0, err
}
return buf.WriteTo(w)
}
-const loader = `package {{ .Package }}
+const loader = `package {{ .package }}
import (
"encoding/base64"
@@ -120,22 +129,30 @@ import (
"io/ioutil"
)
-func {{ .FName }}(n string) ([]byte, error) {
+func {{ .function }}(n string) ([]byte, error) {
var templates = map[string]string {
-{{- range $name, $data := .Templates }}
+{{- range $name, $data := .templates }}
"{{ $name }}": ` + "`" + `{{ $data }}` + "`" + `,
{{- end }}
}
d, ok := templates[n]
if !ok {
- return nil, fmt.Errorf("template not found")
+ return nil, fmt.Errorf("template %q not found", n)
}
// Check for overriding file
- b, err := ioutil.ReadFile("{{ .Base }}" + n + "{{ .Extension }}")
+ b, err := ioutil.ReadFile("{{ .base }}" + n + "{{ .extension }}")
if err == nil && b != nil {
return b, nil
}
return base64.StdEncoding.DecodeString(d)
}
+
+func {{ .function }}Must(n string) []byte {
+ b, err := {{ .function }}(n)
+ if err != nil {
+ panic(err)
+ }
+ return b
+}
`