transmet/templates.go

66 lines
1.6 KiB
Go
Raw Normal View History

package main
import (
"fmt"
"html/template"
"path/filepath"
"regexp"
"net/http"
2015-05-23 17:49:27 +00:00
"errors"
)
var (
templates = map[string]*template.Template{}
)
2015-05-23 17:49:27 +00:00
// template helper function
func dict (values ...interface{}) (map[string]interface{}, error) {
if len(values)%2 != 0 {
return nil, errors.New("invalid dict call")
}
dict := make(map[string]interface{}, len(values)/2)
for i := 0; i < len(values); i+=2 {
key, ok := values[i].(string)
if !ok {
return nil, errors.New("dict keys must be strings")
}
dict[key] = values[i+1]
}
return dict, nil
}
func stringTimes(times int, str string) string {
result := ""
for i := 0; i < times; i ++ {
result += str
}
return result
}
// Tempalte helper functions
var funcMap = template.FuncMap {
"add": func (x, y int) int { return x + y },
"minus": func (x, y int) int { return x - y },
2015-05-23 17:49:27 +00:00
"dict": dict,
"stringTimes": stringTimes,
}
func initTemplates() {
files, _ := filepath.Glob("templates/pages/*.html")
re := regexp.MustCompile("templates/pages/(.*).html")
fmt.Println("Loading Templates:")
for _, t := range files {
name := re.FindStringSubmatch(t)
fmt.Println(" ", name[1])
templates[name[1]] = template.Must(template.New(name[1]).Funcs(funcMap).ParseFiles("templates/layout.html", t))
}
}
func ShowTemplate(template string, w http.ResponseWriter, data map[string]interface{}) {
err := templates[template].ExecuteTemplate(w, "layout.html", data)
if err != nil {
fmt.Println("Exec err: ", err)
}
// TODO: show error 500 page
}