diff options
author | Matthew Lemon <y@yulqen.org> | 2024-02-15 15:43:04 +0000 |
---|---|---|
committer | Matthew Lemon <y@yulqen.org> | 2024-02-15 15:43:04 +0000 |
commit | dd24746bcde550cffaf698a0c9c727e869e3cfb3 (patch) | |
tree | 5321ea481b1c214c38654bf36f152f763f4de1bd /cmd/web/helpers.go | |
parent | c8065a2fcd2386b96eaa1521513afe3f9ba59770 (diff) |
Implemented template cache
This is not perfect.
At the moment, the new render() function, introduced in this commit,
expects a templateData{} struct which contains an Operations field. This
will need to be made generic, or we have multiple render() functions to
accommdate the different types of data struct we want to be able to pass
to templates.
Also, in this commit I had to get rid of the /pages/operations and
/pages/organisation sub directories for now. This does not fit the
newTemplateCache() function - also introduced here. This needs to be
refactored if we want to have subdirectories of templates - or else we
stick to putting them inside pages/ and we name them appropriately, as
we have done here with operations_list and organisation_list templates.
Diffstat (limited to 'cmd/web/helpers.go')
-rw-r--r-- | cmd/web/helpers.go | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/cmd/web/helpers.go b/cmd/web/helpers.go index 5f7e4d3..fc9b8f8 100644 --- a/cmd/web/helpers.go +++ b/cmd/web/helpers.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "log" "net/http" "runtime/debug" @@ -29,3 +30,23 @@ func (app *application) clientError(w http.ResponseWriter, status int) { func (app *application) notFound(w http.ResponseWriter) { app.clientError(w, http.StatusNotFound) } + +func (app *application) render(w http.ResponseWriter, r *http.Request, status int, page string, data templateData) { + // retrieve the appropriate template set from the cache based on the page name. + // If no entry exists in the cache with the provided name, create a new error + // and call serverError() helper that we made earlier and return. + ts, ok := app.templateCache[page] + if !ok { + err := fmt.Errorf("the template %s does not exist", page) + app.serverError(w, r, err) + return + } + + // Write out the provided HTTP status code('200 OK', '400 Bad Request', etc). + w.WriteHeader(status) + + err := ts.ExecuteTemplate(w, "base", data) + if err != nil { + app.serverError(w, r, err) + } +} |