filebrowser/page/page.go

70 lines
1.2 KiB
Go
Raw Normal View History

2015-09-13 11:14:18 +00:00
package page
import (
2015-09-14 09:46:31 +00:00
"log"
2015-09-13 11:14:18 +00:00
"net/http"
2015-09-17 16:41:31 +00:00
"text/template"
2015-09-13 11:14:18 +00:00
"github.com/hacdias/caddy-hugo/assets"
2015-09-14 09:46:31 +00:00
"github.com/hacdias/caddy-hugo/utils"
2015-09-13 11:14:18 +00:00
)
const (
templateExtension = ".tmpl"
)
2015-09-13 21:48:52 +00:00
var funcMap = template.FuncMap{
2015-09-14 09:46:31 +00:00
"splitCapitalize": utils.SplitCapitalize,
2015-09-13 21:48:52 +00:00
}
// Page type
type Page struct {
2015-09-17 16:41:31 +00:00
Name string
Body interface{}
2015-09-13 11:14:18 +00:00
}
// Render the page
2015-09-14 17:18:26 +00:00
func (p *Page) Render(w http.ResponseWriter, r *http.Request, templates ...string) (int, error) {
2015-09-17 16:41:31 +00:00
tpl, err := GetTemplate(r, templates...)
if err != nil {
log.Print(err)
return 500, err
}
tpl.Execute(w, p)
return 200, nil
}
func GetTemplate(r *http.Request, templates ...string) (*template.Template, error) {
2015-09-16 20:48:08 +00:00
if r.Header.Get("X-PJAX") == "true" {
2015-09-14 17:18:26 +00:00
templates = append(templates, "base_minimal")
} else {
templates = append(templates, "base_full")
}
2015-09-14 13:00:12 +00:00
var tpl *template.Template
for i, t := range templates {
page, err := assets.Asset("templates/" + t + templateExtension)
if err != nil {
log.Print(err)
2015-09-17 16:41:31 +00:00
return new(template.Template), err
2015-09-14 13:00:12 +00:00
}
if i == 0 {
tpl, err = template.New(t).Funcs(funcMap).Parse(string(page))
} else {
tpl, err = tpl.Parse(string(page))
}
if err != nil {
log.Print(err)
2015-09-17 16:41:31 +00:00
return new(template.Template), err
2015-09-14 13:00:12 +00:00
}
2015-09-13 11:14:18 +00:00
}
2015-09-17 16:41:31 +00:00
return tpl, nil
2015-09-13 11:14:18 +00:00
}