refactor views

master
Jason Staten 2 years ago
parent 3dce44a652
commit 7e01f3937d

@ -2,38 +2,17 @@ package main
import (
"embed"
"html/template"
"io"
"log"
"math/rand"
"net/http"
"strconv"
)
//go:embed views/*.html
var tmplFS embed.FS
"jxs.me/todogo/views"
)
//go:embed public/*
var publicFS embed.FS
type Template struct {
templates *template.Template
}
func New() *Template {
templates := template.Must(template.New("").ParseFS(tmplFS, "views/*.html"))
return &Template{
templates: templates,
}
}
func (t *Template) Render(w io.Writer, name string, data any) error {
tmpl := template.Must(t.templates.Clone())
tmpl = template.Must(tmpl.ParseFS(tmplFS, "views/"+name))
return tmpl.ExecuteTemplate(w, "layout.html", data)
}
type Todo struct {
Id string
Title string
@ -72,7 +51,8 @@ func countSlice[T any](xs []T, pred func(T) bool) int {
func main() {
todos := make([]Todo, 0, 10)
t := New()
t := views.New()
list := t.Renderer("list.html")
http.Handle("/public/", http.FileServer(http.FS(publicFS)))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
@ -94,10 +74,7 @@ func main() {
Only: only,
Incomplete: incomplete,
}
err := t.Render(w, "list.html", vm)
if err != nil {
log.Println(err)
}
list(w, r, vm)
})
http.HandleFunc("/todo", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {

@ -0,0 +1,36 @@
package views
import (
"embed"
"html/template"
"log"
"net/http"
)
//go:embed *.html
var tmplFS embed.FS
func New() *Views {
templates := template.Must(template.New("").ParseFS(tmplFS, "*.html"))
return &Views{
templates: templates,
}
}
type Views struct {
templates *template.Template
}
func (v *Views) Renderer(name string) func(w http.ResponseWriter, r *http.Request, data any) {
tmpl := template.Must(v.templates.Clone())
tmpl = template.Must(tmpl.ParseFS(tmplFS, name))
return func(w http.ResponseWriter, r *http.Request, data any) {
err := tmpl.ExecuteTemplate(w, "layout.html", data)
if err != nil {
w.WriteHeader(500)
log.Print(err)
}
}
}
Loading…
Cancel
Save