89 lines
1.8 KiB
Go
89 lines
1.8 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"html/template"
|
||
|
"io"
|
||
|
"mime"
|
||
|
"path"
|
||
|
"path/filepath"
|
||
|
"strings"
|
||
|
|
||
|
"git.fuyu.moe/Fuyu/router"
|
||
|
"git.fuyu.moe/Tracreed/mal-importer/internal/static"
|
||
|
"git.fuyu.moe/Tracreed/mal-importer/internal/templates"
|
||
|
)
|
||
|
|
||
|
// Renderer rendders templates
|
||
|
type Renderer struct {
|
||
|
templates map[string]*template.Template
|
||
|
}
|
||
|
|
||
|
// NewRenderer loads all templates
|
||
|
func NewRenderer() *Renderer {
|
||
|
t := &Renderer{}
|
||
|
if t.templates == nil {
|
||
|
t.templates = make(map[string]*template.Template)
|
||
|
}
|
||
|
|
||
|
components := template.New(``)
|
||
|
pages := []string{}
|
||
|
for _, v := range templates.AssetNames() {
|
||
|
if strings.HasPrefix(v, `pages/`) {
|
||
|
pages = append(pages, v)
|
||
|
continue
|
||
|
}
|
||
|
|
||
|
data, err := templates.Asset(v)
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
template.Must(components.New(v).Parse(string(data)))
|
||
|
}
|
||
|
|
||
|
for _, page := range pages {
|
||
|
data, err := templates.Asset(page)
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
tmpl, _ := components.Clone()
|
||
|
|
||
|
name := removeExt(strings.TrimPrefix(page, `pages/`))
|
||
|
t.templates[name] = template.Must(tmpl.New(page).Parse(string(data)))
|
||
|
}
|
||
|
|
||
|
return t
|
||
|
}
|
||
|
|
||
|
// Render implements echo's Renderer interface
|
||
|
func (t *Renderer) Render(w io.Writer, name string, data interface{}, c *router.Context) error {
|
||
|
tmpl, ok := t.templates[name]
|
||
|
if !ok {
|
||
|
return fmt.Errorf(`template '%s' not found`, name)
|
||
|
}
|
||
|
|
||
|
templateData := struct {
|
||
|
Content interface{}
|
||
|
}{data}
|
||
|
|
||
|
return tmpl.ExecuteTemplate(w, `base`, templateData)
|
||
|
}
|
||
|
|
||
|
func removeExt(s string) string {
|
||
|
return strings.TrimSuffix(s, path.Ext(s))
|
||
|
}
|
||
|
|
||
|
func getStatic(c *router.Context) error {
|
||
|
path := path.Clean(strings.TrimPrefix(c.Request.URL.Path, `/static/`))
|
||
|
|
||
|
data, err := static.Asset(path)
|
||
|
if err != nil {
|
||
|
return c.String(404, `Resource not found`)
|
||
|
}
|
||
|
|
||
|
c.Response.Header().Set(`Content-Type`, mime.TypeByExtension(filepath.Ext(path)))
|
||
|
_, _ = c.Response.Write(data)
|
||
|
|
||
|
return nil
|
||
|
}
|