2015-09-13 11:14:18 +00:00
|
|
|
package page
|
|
|
|
|
|
|
|
import (
|
|
|
|
"html/template"
|
|
|
|
"net/http"
|
2015-09-13 21:48:52 +00:00
|
|
|
"reflect"
|
2015-09-13 11:14:18 +00:00
|
|
|
"strings"
|
2015-09-13 21:48:52 +00:00
|
|
|
"unicode"
|
2015-09-13 11:14:18 +00:00
|
|
|
|
|
|
|
"github.com/hacdias/caddy-hugo/assets"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
templateExtension = ".tmpl"
|
|
|
|
headerMark = "{{#HEADER#}}"
|
|
|
|
footerMark = "{{#FOOTER#}}"
|
|
|
|
)
|
|
|
|
|
2015-09-13 21:48:52 +00:00
|
|
|
var funcMap = template.FuncMap{
|
|
|
|
"splitCapitalize": splitCapitalize,
|
|
|
|
"isMap": isMap,
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: utilspackage
|
|
|
|
func isMap(sth interface{}) bool {
|
|
|
|
return reflect.ValueOf(sth).Kind() == reflect.Map
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: utils package
|
|
|
|
func splitCapitalize(name string) string {
|
|
|
|
var words []string
|
|
|
|
l := 0
|
|
|
|
for s := name; s != ""; s = s[l:] {
|
|
|
|
l = strings.IndexFunc(s[1:], unicode.IsUpper) + 1
|
|
|
|
if l <= 0 {
|
|
|
|
l = len(s)
|
|
|
|
}
|
|
|
|
words = append(words, s[:l])
|
|
|
|
}
|
|
|
|
|
|
|
|
name = ""
|
|
|
|
|
|
|
|
for _, element := range words {
|
|
|
|
name += element + " "
|
|
|
|
}
|
|
|
|
|
|
|
|
name = strings.ToLower(name[:len(name)-1])
|
|
|
|
name = strings.ToUpper(string(name[0])) + name[1:len(name)]
|
|
|
|
|
|
|
|
return name
|
|
|
|
}
|
|
|
|
|
2015-09-13 11:28:26 +00:00
|
|
|
// Page type
|
|
|
|
type Page struct {
|
2015-09-13 11:14:18 +00:00
|
|
|
Title string
|
|
|
|
Body interface{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Render the page
|
2015-09-13 11:28:26 +00:00
|
|
|
func (p *Page) Render(name string, w http.ResponseWriter) (int, error) {
|
2015-09-13 11:14:18 +00:00
|
|
|
rawHeader, err := assets.Asset("templates/header" + templateExtension)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return 500, err
|
|
|
|
}
|
|
|
|
|
|
|
|
header := string(rawHeader)
|
|
|
|
|
|
|
|
rawFooter, err := assets.Asset("templates/footer" + templateExtension)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return 500, err
|
|
|
|
}
|
|
|
|
|
|
|
|
footer := string(rawFooter)
|
|
|
|
|
|
|
|
rawPage, err := assets.Asset("templates/" + name + templateExtension)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return 500, err
|
|
|
|
}
|
|
|
|
|
|
|
|
page := string(rawPage)
|
|
|
|
page = strings.Replace(page, headerMark, header, -1)
|
|
|
|
page = strings.Replace(page, footerMark, footer, -1)
|
|
|
|
|
2015-09-13 21:48:52 +00:00
|
|
|
tpl, err := template.New("page").Funcs(funcMap).Parse(page)
|
2015-09-13 11:14:18 +00:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return 500, err
|
|
|
|
}
|
|
|
|
|
|
|
|
tpl.Execute(w, p)
|
|
|
|
return 200, nil
|
|
|
|
}
|