|
|
@ -9,17 +9,19 @@ import ( |
|
|
|
"os" |
|
|
|
"path" |
|
|
|
|
|
|
|
"git.aiterp.net/AiteRP/aitestory/server" |
|
|
|
"git.aiterp.net/gisle/wrouter/response" |
|
|
|
) |
|
|
|
|
|
|
|
var wd, _ = os.Getwd() |
|
|
|
var rootPath = path.Join(wd, "./view/templates/") |
|
|
|
var cache = make(map[string]*template.Template) |
|
|
|
var argsCache = make(map[string][]string) |
|
|
|
|
|
|
|
// 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, fragments ...string) { |
|
|
|
rootPath := server.Main.Config.Directories.Templates |
|
|
|
|
|
|
|
for i, fragment := range fragments { |
|
|
|
fragments[i] = path.Join(rootPath, fragment+".tmpl") |
|
|
|
} |
|
|
@ -38,16 +40,23 @@ func Register(name string, base string, fragments ...string) { |
|
|
|
// 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 |
|
|
|
} |
|
|
|
var tmpl *template.Template |
|
|
|
var err error |
|
|
|
|
|
|
|
tmpl, err := template.New(name).ParseFiles(argsCache[name]...) |
|
|
|
if err != nil { |
|
|
|
response.Text(w, 500, "Failed to run template "+name+": "+err.Error()) |
|
|
|
return |
|
|
|
if server.Main.Config.Server.Debug { |
|
|
|
tmpl, err = template.New(name).ParseFiles(argsCache[name]...) |
|
|
|
if err != nil { |
|
|
|
response.Text(w, 500, "Failed to run template "+name+": "+err.Error()) |
|
|
|
return |
|
|
|
} |
|
|
|
} else { |
|
|
|
var ok bool |
|
|
|
|
|
|
|
tmpl, ok = cache[name] |
|
|
|
if !ok { |
|
|
|
response.Text(w, 500, "Template not found: "+name) |
|
|
|
return |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
w.WriteHeader(status) |
|
|
|