2022-05-21 07:27:51 +00:00
|
|
|
package templates
|
|
|
|
|
|
|
|
import (
|
|
|
|
"embed"
|
|
|
|
"html/template"
|
2022-05-21 20:51:47 +00:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"go.uber.org/zap"
|
2022-05-21 07:27:51 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
//go:embed views/*.html
|
|
|
|
var tmplFS embed.FS
|
|
|
|
|
2022-05-21 20:51:47 +00:00
|
|
|
var (
|
|
|
|
Index = parse("views/index.html")
|
|
|
|
Dashboard = parse("views/dashboard.html")
|
|
|
|
)
|
|
|
|
|
|
|
|
func parse(file string) *template.Template {
|
|
|
|
return template.Must(template.New("base.html").ParseFS(tmplFS, "views/base.html", file))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Renderer renders HTML templates, and logs any errors.
|
|
|
|
type Renderer struct {
|
|
|
|
logger *zap.SugaredLogger
|
|
|
|
}
|
2022-05-21 07:27:51 +00:00
|
|
|
|
2022-05-21 20:51:47 +00:00
|
|
|
func NewRenderer(logger *zap.SugaredLogger) *Renderer {
|
|
|
|
return &Renderer{logger: logger}
|
2022-05-21 07:27:51 +00:00
|
|
|
}
|
|
|
|
|
2022-05-21 20:51:47 +00:00
|
|
|
// Render renders an HTML template to an http.ResponseWriter.
|
|
|
|
func (r *Renderer) Render(w http.ResponseWriter, template *template.Template, data any) {
|
|
|
|
if err := template.Execute(w, data); err != nil {
|
|
|
|
r.logger.With("err", err).Error("error rendering template")
|
|
|
|
http.Error(w, "error rendering template", http.StatusInternalServerError)
|
|
|
|
}
|
2022-05-21 07:27:51 +00:00
|
|
|
}
|