Skip to content

Commit

Permalink
Lazily initialize templates.
Browse files Browse the repository at this point in the history
  • Loading branch information
vmihailenco committed Jul 1, 2013
1 parent ed7c951 commit 18e6ab6
Showing 1 changed file with 33 additions and 10 deletions.
43 changes: 33 additions & 10 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,40 @@ import (
"os"
"path"
"reflect"
"sync"
)

var (
WidgetTemplate = newTemplate(rootDir() + "templates/gforms/widget.html")
CheckboxTemplate = newTemplate(rootDir() + "templates/gforms/checkbox.html")
RadioTemplate = newTemplate(rootDir() + "templates/gforms/radio.html")
type templatesMap struct {
L sync.RWMutex
M map[string]*template.Template
}

var emptyHTML = template.HTML("")

var templates = &templatesMap{
M: make(map[string]*template.Template),
}

emptyHTML = template.HTML("")
var (
WidgetTemplatePath = rootDir() + "templates/gforms/widget.html"
CheckboxTemplatePath = rootDir() + "templates/gforms/checkbox.html"
RadioTemplatePath = rootDir() + "templates/gforms/radio.html"
)

func rootDir() string {
return os.Getenv("ROOT_DIR")
}

func newTemplate(filepath string) *template.Template {
t := template.New(path.Base(filepath))
func getTemplate(filepath string) *template.Template {
templates.L.RLock()
t, ok := templates.M[filepath]
if ok {
templates.L.RUnlock()
return t
}
templates.L.RUnlock()

t = template.New(path.Base(filepath))
t = t.Funcs(template.FuncMap{
"field": RenderField,
"label": RenderLabel,
Expand All @@ -32,6 +50,11 @@ func newTemplate(filepath string) *template.Template {
if err != nil {
panic(err)
}

templates.L.Lock()
templates.M[filepath] = t
templates.L.Unlock()

return t
}

Expand Down Expand Up @@ -71,12 +94,12 @@ func Render(field Field, attrs ...string) (template.HTML, error) {
case *HiddenWidget:
return RenderField(field, attrs)
case *CheckboxWidget:
t = CheckboxTemplate
t = getTemplate(CheckboxTemplatePath)
case *RadioWidget:
data.Radios = widget.Radios(attrs, field.(SingleValueField).StringValue())
t = RadioTemplate
t = getTemplate(RadioTemplatePath)
default:
t = WidgetTemplate
t = getTemplate(WidgetTemplatePath)
}

buf := &bytes.Buffer{}
Expand Down

0 comments on commit 18e6ab6

Please sign in to comment.