dip/templates.go

46 lines
1.1 KiB
Go

package main
import (
"fmt"
"html/template"
"io"
"strings"
"github.com/gobuffalo/packr"
"github.com/labstack/echo/v4"
)
// Template is a template struct
type Template struct {
templates *template.Template
}
// Render is a method that render templates
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
if strings.HasSuffix(name, ".html") {
c.Response().Header().Set(echo.HeaderContentType, echo.MIMETextHTMLCharsetUTF8)
} else if strings.HasSuffix(name, ".js") {
c.Response().Header().Set(echo.HeaderContentType, echo.MIMETextPlain)
} else if strings.HasSuffix(name, ".css") {
c.Response().Header().Set(echo.HeaderContentType, echo.MIMETextPlain)
}
return t.templates.ExecuteTemplate(w, name, data)
}
// BuildTemplates converts packr packages to html/template
func BuildTemplates(box packr.Box) (builttemplates *Template, err error) {
tmpl := template.New("template")
for _, filename := range box.List() {
fmt.Println(filename)
tmplContent, _ := box.FindString(filename)
tmpl.New(filename).Parse(tmplContent)
}
builttemplate := &Template{
templates: tmpl,
}
return builttemplate, nil
}