mirror of
https://github.com/astaxie/beego.git
synced 2025-07-04 03:40:18 +00:00
add template test and cache module
This commit is contained in:
68
template.go
68
template.go
@ -3,18 +3,27 @@ package beego
|
||||
//@todo add template funcs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/russross/blackfriday"
|
||||
"html/template"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var beegoTplFuncMap template.FuncMap
|
||||
var (
|
||||
beegoTplFuncMap template.FuncMap
|
||||
BeeTemplates map[string]*template.Template
|
||||
BeeTemplateExt string
|
||||
)
|
||||
|
||||
func init() {
|
||||
BeeTemplates = make(map[string]*template.Template)
|
||||
beegoTplFuncMap = make(template.FuncMap)
|
||||
BeeTemplateExt = "tpl"
|
||||
beegoTplFuncMap["markdown"] = MarkDown
|
||||
beegoTplFuncMap["dateformat"] = DateFormat
|
||||
beegoTplFuncMap["date"] = Date
|
||||
@ -87,8 +96,61 @@ func Compare(a, b interface{}) (equal bool) {
|
||||
// AddFuncMap let user to register a func in the template
|
||||
func AddFuncMap(key string, funname interface{}) error {
|
||||
if _, ok := beegoTplFuncMap[key]; ok {
|
||||
return errors.New("funcmap already has the key")
|
||||
return errors.New("funcmap already has the key")
|
||||
}
|
||||
beegoTplFuncMap[key] = funname
|
||||
return nil
|
||||
}
|
||||
|
||||
type templatefile struct {
|
||||
root string
|
||||
files map[string][]string
|
||||
}
|
||||
|
||||
func (self *templatefile) visit(paths string, f os.FileInfo, err error) error {
|
||||
if f == nil {
|
||||
return err
|
||||
}
|
||||
if f.IsDir() {
|
||||
return nil
|
||||
} else if (f.Mode() & os.ModeSymlink) > 0 {
|
||||
return nil
|
||||
} else {
|
||||
if strings.HasSuffix(paths, BeeTemplateExt) {
|
||||
a := []byte(paths)
|
||||
a = a[len([]byte(self.root)):]
|
||||
subdir := path.Dir(strings.TrimLeft(string(a), "/"))
|
||||
if _, ok := self.files[subdir]; ok {
|
||||
self.files[subdir] = append(self.files[subdir], paths)
|
||||
} else {
|
||||
m := make([]string, 1)
|
||||
m[0] = paths
|
||||
self.files[subdir] = m
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func SetGlobalTemplateExt(ext string) {
|
||||
BeeTemplateExt = ext
|
||||
}
|
||||
|
||||
func BuildTemplate(dir string) error {
|
||||
self := templatefile{
|
||||
root: dir,
|
||||
files: make(map[string][]string),
|
||||
}
|
||||
err := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
|
||||
return self.visit(path, f, err)
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Printf("filepath.Walk() returned %v\n", err)
|
||||
return err
|
||||
}
|
||||
for k, v := range self.files {
|
||||
BeeTemplates[k] = template.Must(template.New("beegoTemplate" + k).Funcs(beegoTplFuncMap).ParseFiles(v...))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user