Created
November 28, 2015 07:12
-
-
Save gebv/fe40d066bd6a2261c341 to your computer and use it in GitHub Desktop.
manager templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package core | |
| import ( | |
| "bytes" | |
| "github.com/golang/glog" | |
| "html/template" | |
| "os" | |
| "path/filepath" | |
| ) | |
| var Templates map[string]*template.Template | |
| var TemplatePath string | |
| func init() { | |
| Templates = make(map[string]*template.Template) | |
| TemplatePath = os.Getenv("TEMPLATE_PATH") | |
| if len(TemplatePath) == 0 { | |
| glog.Errorln("Не задан путь к шаблонам (TEMPLATE_PATH)") | |
| } | |
| if _, err := os.Stat(TemplatePath); err != nil { | |
| if os.IsNotExist(err) { | |
| glog.Error("Не найдена папка с дирикториями", err) | |
| } else { | |
| glog.Error("Ошибка открытия папки с дирикториями", err) | |
| } | |
| } | |
| allFiles := make(map[string]string) | |
| layoutPath := "" | |
| err := filepath.Walk(TemplatePath, func(path string, f os.FileInfo, err error) error { | |
| if !f.IsDir() { | |
| if f.Name() == "layout.tpl" { | |
| layoutPath = path | |
| } else { | |
| allFiles[filepath.Base(f.Name())] = path | |
| } | |
| } | |
| return nil | |
| }) | |
| if layoutPath == "" { | |
| glog.Error("Не зада layout") | |
| os.Exit(-1) | |
| } | |
| if err != nil { | |
| glog.Error("Ошибка templates", err) | |
| os.Exit(-1) | |
| } | |
| for templateName, templatePath := range allFiles { | |
| Templates[templateName] = template.Must(template.ParseFiles(layoutPath, templatePath)) | |
| } | |
| } | |
| func buildTemplate(name string, data map[interface{}]interface{}) string { | |
| newbytes := bytes.NewBufferString("") | |
| tmpl, ok := Templates[name] | |
| if !ok { | |
| glog.Error("Not found template ", name) | |
| return "" | |
| } | |
| if err := tmpl.ExecuteTemplate(newbytes, "base", data); err != nil { | |
| glog.Error("Ошибка компиляции шаблона ", name, err) | |
| return "" | |
| } | |
| return newbytes.String() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment