package main import ( "fmt" "html/template" "io" "mime" "path" "path/filepath" "strings" "git.fuyu.moe/Crow/echoBoilerplate/internal/static" "git.fuyu.moe/Crow/echoBoilerplate/internal/templates" "github.com/labstack/echo" ) // Reset reads all the templates func (t *Template) Reset() { 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(page) t.templates[name] = template.Must(tmpl.New(page).Parse(string(data))) } } // Render echo Render func func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error { tmpl, ok := t.templates[name] if !ok { return fmt.Errorf("template '%s' not found", name) } return tmpl.ExecuteTemplate(w, "base", data) } func removeExt(s string) string { return strings.TrimSuffix(s, path.Ext(s)) } func getStatic(c echo.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 }