filebrowser/page/page.go

81 lines
1.7 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-17 20:26:06 +00:00
"isMarkdown": utils.IsMarkdownFile,
2015-09-13 21:48:52 +00:00
}
// Page type
type Page struct {
2015-09-18 08:47:02 +00:00
Name string
Class 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
}
2015-09-18 08:47:02 +00:00
// GetTemplate is used to get a ready to use template based on the url and on
// other sent templates
2015-09-17 16:41:31 +00:00
func GetTemplate(r *http.Request, templates ...string) (*template.Template, error) {
2015-09-18 08:47:02 +00:00
// If this is a pjax request, use the minimal template to send only
// the main content
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
2015-09-18 08:47:02 +00:00
// For each template, add it to the the tpl variable
2015-09-14 13:00:12 +00:00
for i, t := range templates {
2015-09-18 08:47:02 +00:00
// Get the template from the assets
2015-09-14 13:00:12 +00:00
page, err := assets.Asset("templates/" + t + templateExtension)
2015-09-18 08:47:02 +00:00
// Check if there is some error. If so, the template doesn't exist
2015-09-14 13:00:12 +00:00
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-18 08:47:02 +00:00
// If it's the first iteration, creates a new template and add the
// functions map
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
}