0
0
Fork 0
zero-blog/template.go

52 lines
1.2 KiB
Go

package main
import (
"errors"
"html/template"
"io/ioutil"
"log"
"path/filepath"
"os"
)
var (
Templates *template.Template // all templates
base_path_len int // the base path len to generate a template name
)
// load all templates in the path
func templates_load(path string) error {
if base_path_len > 0 { return errors.New("Templates already loaded!") }
if len(path) == 0 { return errors.New("Path is empty!") }
base_path_len = len(path)
Templates = template.New("dummy")
if err := filepath.Walk(path, templates_scan_file); err != nil {
return err
}
return nil
}
// scan the file for a useable name and add to template collection
func templates_scan_file(path string, info os.FileInfo, err error) error {
if err != nil { log.Println(`Error with file:`, path, `-`, err) }
if !info.IsDir() && path[len(path) - 5:] == `.tmpl` {
name := path[base_path_len + 1 : len(path) - 5]
template.Must(Templates.New(name).Parse(template_parse(path)))
if err != nil {
return err
}
}
return nil
}
// parse the template or return an error
func template_parse(path string) string {
content, err := ioutil.ReadFile(path)
if err != nil {
return ""
}
return string(content)
}