diff options
| author | herkulessi <git@herkulessi.de> | 2025-08-20 20:13:09 +0200 |
|---|---|---|
| committer | herkulessi <git@herkulessi.de> | 2025-08-20 20:13:09 +0200 |
| commit | 32e7fe5f94eee7e08f048d1ead1e7e82f29c46d6 (patch) | |
| tree | bb93bfa26873ad55b51b12398e837bd2ea880b50 /templates.go | |
Initial commit of libmkwebpage
Diffstat (limited to 'templates.go')
| -rw-r--r-- | templates.go | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/templates.go b/templates.go new file mode 100644 index 0000000..00c1b31 --- /dev/null +++ b/templates.go @@ -0,0 +1,70 @@ +package libmkwebpage + +import ( + "bytes" + "embed" + "fmt" + "html/template" + "io/fs" + "net/http" +) + +type templates struct { + staticRoot embed.FS + dynamicRoot fs.FS + errorTemplate string + bindings template.FuncMap +} + +func (w *Webpage) getTemplateRoot() fs.FS { + if w.isDynamic() { + return w.templates.dynamicRoot + } + return w.templates.staticRoot +} + +func (w *Webpage) NewTemplates(static embed.FS, dynamic fs.FS) *Webpage { + w.templates = templates{staticRoot: static, dynamicRoot: dynamic, bindings: template.FuncMap{}} + return w +} +func (w *Webpage) SetErrorTemplate(path string) { + w.templates.errorTemplate = path +} +func (w *Webpage) Error(writer http.ResponseWriter, code int, err error) { + writer.WriteHeader(code) + if w.templates.errorTemplate == "" { + fmt.Fprintln(writer, err) + } +} +func (w *Webpage) InternalServerError(writer http.ResponseWriter, err error) { + w.Error(writer, http.StatusInternalServerError, err) +} +func (w *Webpage) BadRequest(writer http.ResponseWriter, err error) { + w.Error(writer, http.StatusInternalServerError, err) +} +func (w *Webpage) BindTemplateFunc(name string, fun any) *Webpage { + w.templates.bindings[name] = fun + return w +} + +func (w *Webpage) RenderTemplate(writer http.ResponseWriter, name string, data any) { + writer.Header().Set("Content-Type", "text/html; charset=utf-8") + tmpl, err := fs.ReadFile(w.getTemplateRoot(), "templates/"+name+".tmpl") + if err != nil { + panic(err) + } + if err := template.Must(template.New("templates/"+name+".tmpl").Funcs(w.templates.bindings).Parse(string(tmpl))).Execute(writer, data); err != nil { + panic(err) + } +} +func (w *Webpage) RenderTemplateToString(name string, data any) string { + buf := bytes.NewBuffer(nil) + tmpl, err := fs.ReadFile(w.getTemplateRoot(), "templates/"+name+".tmpl") + if err != nil { + panic(err) + } + if err := template.Must(template.New("templates/"+name+".tmpl").Funcs(w.templates.bindings).Parse(string(tmpl))).Execute(buf, data); err != nil { + panic(err) + } + return buf.String() +} |
