1
0
mirror of https://github.com/astaxie/beego.git synced 2024-12-23 08:10:50 +00:00

Merge pull request #1762 from saturn4er/htmlEngines

Implemented possibility to add custom template engines
This commit is contained in:
astaxie 2016-03-30 16:43:39 +08:00
commit ccc84dd8eb

View File

@ -33,10 +33,12 @@ import (
var (
beegoTplFuncMap = make(template.FuncMap)
// beeTemplates caching map and supported template file extensions.
beeTemplates = make(map[string]*template.Template)
beeTemplates = make(map[string]TemplateRenderer)
templatesLock sync.RWMutex
// beeTemplateExt stores the template extension which will build
beeTemplateExt = []string{"tpl", "html"}
// beeTemplatePreprocessors stores associations of extension -> preprocessor handler
beeTemplateEngines = map[string]templateHandler{}
)
func executeTemplate(wr io.Writer, name string, data interface{}) error {
@ -89,6 +91,10 @@ func AddFuncMap(key string, fn interface{}) error {
return nil
}
type templateHandler func(root, path string, funcs template.FuncMap) (TemplateRenderer, error)
type TemplateRenderer interface {
ExecuteTemplate(wr io.Writer, name string, data interface{}) error
}
type templateFile struct {
root string
files map[string][]string
@ -157,11 +163,20 @@ func BuildTemplate(dir string, files ...string) error {
fmt.Printf("filepath.Walk() returned %v\n", err)
return err
}
buildAllFiles := len(files) == 0
for _, v := range self.files {
for _, file := range v {
if len(files) == 0 || utils.InSlice(file, files) {
if buildAllFiles || utils.InSlice(file, files) {
templatesLock.Lock()
t, err := getTemplate(self.root, file, v...)
ext := filepath.Ext(file)
var t TemplateRenderer
if len(ext) == 0 {
t, err = getTemplate(self.root, file, v...)
} else if fn, ok := beeTemplateEngines[ext[1:]]; ok {
t, err = fn(self.root, file, beegoTplFuncMap)
} else {
t, err = getTemplate(self.root, file, v...)
}
if err != nil {
logs.Trace("parse template err:", file, err)
} else {
@ -306,3 +321,9 @@ func DelStaticPath(url string) *App {
delete(BConfig.WebConfig.StaticDir, url)
return BeeApp
}
func AddTemplateEngine(extension string, fn templateHandler) *App {
AddTemplateExt(extension)
beeTemplateEngines[extension] = fn
return BeeApp
}