You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.4 KiB
59 lines
1.4 KiB
package view
|
|
|
|
import (
|
|
"errors"
|
|
"html/template"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
|
|
"git.aiterp.net/gisle/wrouter/response"
|
|
)
|
|
|
|
var wd, _ = os.Getwd()
|
|
var rootPath = path.Join(wd, "./view/templates/")
|
|
var cache = make(map[string]*template.Template)
|
|
|
|
// Register registers a template and compiles it for rendering. This should be done
|
|
// in the beginning since an error will terminate the server
|
|
func Register(name string, base string) {
|
|
tmpl, err := template.New(name).ParseFiles(path.Join(rootPath, name+".tmpl"), path.Join(rootPath, base+".tmpl"))
|
|
if err != nil {
|
|
log.Fatalf("Failed to register %s: %s", name, err)
|
|
}
|
|
|
|
cache[name] = tmpl
|
|
}
|
|
|
|
// Render renders a template with the name it was registered with, and with the
|
|
// view model. The view model is expected to be the correct model from the viewmodel
|
|
// package
|
|
func Render(w http.ResponseWriter, name string, status int, viewModel interface{}) {
|
|
tmpl, ok := cache[name]
|
|
if !ok {
|
|
response.Text(w, 500, "Template not found: "+name)
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(status)
|
|
err := tmpl.ExecuteTemplate(w, "base", viewModel)
|
|
if err != nil {
|
|
log.Println("Template error:", err.Error())
|
|
}
|
|
}
|
|
|
|
// Run runs the template to a simple io.Writer. It's made for testing
|
|
func Run(w io.Writer, name string, viewModel interface{}) error {
|
|
tmpl, ok := cache[name]
|
|
if !ok {
|
|
return errors.New("template not found")
|
|
}
|
|
|
|
return tmpl.ExecuteTemplate(w, "base", viewModel)
|
|
}
|
|
|
|
func init() {
|
|
Register("index", "base/default")
|
|
}
|