filebrowser/tools/templates/templates.go

74 lines
1.6 KiB
Go
Raw Normal View History

2016-03-06 19:18:46 +00:00
package templates
2015-09-14 09:46:31 +00:00
import (
2015-09-18 12:52:10 +00:00
"log"
"net/http"
2015-09-14 09:46:31 +00:00
"strings"
2016-03-06 20:37:49 +00:00
"text/template"
2015-09-18 12:52:10 +00:00
2016-03-06 20:37:49 +00:00
"github.com/hacdias/caddy-hugo/routes/assets"
2015-09-14 09:46:31 +00:00
)
2016-02-07 15:14:56 +00:00
// CanBeEdited checks if the extension of a file is supported by the editor
2015-09-20 21:20:37 +00:00
func CanBeEdited(filename string) bool {
2016-02-07 09:09:22 +00:00
extensions := [...]string{
"md", "markdown", "mdown", "mmark",
"asciidoc", "adoc", "ad",
"rst",
2015-09-20 21:20:37 +00:00
".json", ".toml", ".yaml",
".css", ".sass", ".scss",
".js",
".html",
2016-02-07 15:14:56 +00:00
".txt",
2015-09-20 21:20:37 +00:00
}
for _, extension := range extensions {
if strings.HasSuffix(filename, extension) {
return true
}
}
return false
2015-09-20 21:00:25 +00:00
}
2016-03-06 19:18:46 +00:00
// Get is used to get a ready to use template based on the url and on
2015-09-18 12:52:10 +00:00
// other sent templates
2016-03-06 19:18:46 +00:00
func Get(r *http.Request, functions template.FuncMap, templates ...string) (*template.Template, error) {
2015-09-18 12:52:10 +00:00
// If this is a pjax request, use the minimal template to send only
// the main content
if r.Header.Get("X-PJAX") == "true" {
templates = append(templates, "base_minimal")
} else {
templates = append(templates, "base_full")
}
var tpl *template.Template
// For each template, add it to the the tpl variable
for i, t := range templates {
// Get the template from the assets
page, err := assets.Asset("templates/" + t + ".tmpl")
// Check if there is some error. If so, the template doesn't exist
if err != nil {
log.Print(err)
return new(template.Template), err
}
// If it's the first iteration, creates a new template and add the
// functions map
if i == 0 {
tpl, err = template.New(t).Funcs(functions).Parse(string(page))
} else {
tpl, err = tpl.Parse(string(page))
}
if err != nil {
log.Print(err)
return new(template.Template), err
}
}
return tpl, nil
}