The backend for the AiteStory website
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.

82 lines
2.0 KiB

  1. package view
  2. import (
  3. "errors"
  4. "html/template"
  5. "io"
  6. "log"
  7. "net/http"
  8. "os"
  9. "path"
  10. "git.aiterp.net/AiteRP/aitestory/server"
  11. "git.aiterp.net/gisle/wrouter/response"
  12. )
  13. var wd, _ = os.Getwd()
  14. var cache = make(map[string]*template.Template)
  15. var argsCache = make(map[string][]string)
  16. // Register registers a template and compiles it for rendering. This should be done
  17. // in the beginning since an error will terminate the server
  18. func Register(name string, base string, fragments ...string) {
  19. rootPath := server.Main.Config.Directories.Templates
  20. for i, fragment := range fragments {
  21. fragments[i] = path.Join(rootPath, fragment+".tmpl")
  22. }
  23. args := append([]string{path.Join(rootPath, name+".tmpl"), path.Join(rootPath, base+".tmpl")}, fragments...)
  24. tmpl, err := template.New(name).ParseFiles(args...)
  25. if err != nil {
  26. log.Fatalf("Failed to register %s: %s", name, err)
  27. }
  28. argsCache[name] = args
  29. cache[name] = tmpl
  30. }
  31. // Render renders a template with the name it was registered with, and with the
  32. // view model. The view model is expected to be the correct model from the viewmodel
  33. // package
  34. func Render(w http.ResponseWriter, name string, status int, viewModel interface{}) {
  35. var tmpl *template.Template
  36. var err error
  37. if server.Main.Config.Server.Debug {
  38. tmpl, err = template.New(name).ParseFiles(argsCache[name]...)
  39. if err != nil {
  40. response.Text(w, 500, "Failed to run template "+name+": "+err.Error())
  41. return
  42. }
  43. } else {
  44. var ok bool
  45. tmpl, ok = cache[name]
  46. if !ok {
  47. response.Text(w, 500, "Template not found: "+name)
  48. return
  49. }
  50. }
  51. w.WriteHeader(status)
  52. err = tmpl.ExecuteTemplate(w, "base", viewModel)
  53. if err != nil {
  54. log.Println("Template error:", err.Error())
  55. }
  56. }
  57. // Run runs the template to a simple io.Writer. It's made for testing
  58. func Run(w io.Writer, name string, viewModel interface{}) error {
  59. tmpl, ok := cache[name]
  60. if !ok {
  61. return errors.New("template not found")
  62. }
  63. return tmpl.ExecuteTemplate(w, "base", viewModel)
  64. }
  65. func init() {
  66. Register("index", "base/default")
  67. Register("login", "base/default")
  68. }