summaryrefslogtreecommitdiff
path: root/app/templates.go
blob: 458325405ef494f93a086838f247ed81d6d436af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package app

import (
	"bytes"
	"fmt"
	"html/template"
	"io"
	"log"
	"sync"
)

type templateMap map[string]*template.Template

type templateStore struct {
	sync.Mutex

	base      string
	templates templateMap
}

func newTemplateStore(base string) *templateStore {
	return &templateStore{
		base:      base,
		templates: make(templateMap),
	}
}

func (t *templateStore) Add(name string, template *template.Template) {
	t.Lock()
	defer t.Unlock()

	t.templates[name] = template
}

func (t *templateStore) Exec(name string, ctx interface{}) (io.WriterTo, error) {
	t.Lock()
	defer t.Unlock()

	template, ok := t.templates[name]
	if !ok {
		log.Printf("template %s not found", name)
		return nil, fmt.Errorf("no such template: %s", name)
	}

	buf := bytes.NewBuffer([]byte{})
	err := template.ExecuteTemplate(buf, t.base, ctx)
	if err != nil {
		log.Printf("error parsing template %s: %s", name, err)
		return nil, err
	}

	return buf, nil
}