core/template.go
2024-09-24 16:12:17 -05:00

45 lines
1,013 B
Go

// Copyright (c) 2024 Zeni Kim <zenik@smarteching.com>
// Use of this source code is governed by MIT-style
// license that can be found in the LICENSE file.
package core
import (
"bytes"
"embed"
"fmt"
"html/template"
"io/fs"
"net/http"
"strings"
)
type Template struct {
tmpl *template.Template
}
func (t *Template) NewTemplates(resources embed.FS) {
var paths []string
fs.WalkDir(resources, ".", func(path string, d fs.DirEntry, err error) error {
if strings.Contains(d.Name(), ".html") {
paths = append(paths, path)
}
return nil
})
t.tmpl = template.Must(template.ParseFS(resources, paths...))
}
func (t *Template) Render(w http.ResponseWriter, name string, data interface{}) {
var buffer bytes.Buffer
err := t.tmpl.ExecuteTemplate(&buffer, name, data)
if err != nil {
err = fmt.Errorf("error executing template: %w", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
buffer.WriteTo(w)
}