示例#1
0
文件: handlebars.go 项目: yunhor/iris
// BuildTemplates builds the handlebars templates
func (e *Engine) BuildTemplates() error {
	if e.Config.Extensions == nil || len(e.Config.Extensions) == 0 {
		e.Config.Extensions = []string{".html"}
	}

	// register the global helpers
	if e.Config.Handlebars.Helpers != nil {
		raymond.RegisterHelpers(e.Config.Handlebars.Helpers)
	}

	// the render works like {{ render "myfile.html" theContext.PartialContext}}
	// instead of the html/template engine which works like {{ render "myfile.html"}} and accepts the parent binding, with handlebars we can't do that because of lack of runtime helpers (dublicate error)
	raymond.RegisterHelper("render", func(partial string, binding interface{}) raymond.SafeString {
		contents, err := e.executeTemplateBuf(partial, binding)
		if err != nil {
			return raymond.SafeString("Template with name: " + partial + " couldn't not be found.")
		}
		return raymond.SafeString(contents)
	})

	var templateErr error

	dir := e.Config.Directory
	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if info == nil || info.IsDir() {
			return nil
		}

		rel, err := filepath.Rel(dir, path)
		if err != nil {
			return err
		}

		ext := ""
		if strings.Index(rel, ".") != -1 {
			ext = filepath.Ext(rel)
		}

		for _, extension := range e.Config.Extensions {
			if ext == extension {

				buf, err := ioutil.ReadFile(path)
				contents := string(buf)

				if err != nil {
					templateErr = err
					break
				}

				name := filepath.ToSlash(rel)

				tmpl, err := raymond.Parse(contents)
				if err != nil {
					templateErr = err
					continue
				}
				e.mu.Lock()
				e.templateCache[name] = tmpl
				e.mu.Unlock()

				break
			}
		}
		return nil
	})

	return templateErr

}
示例#2
0
文件: template.go 项目: curx/drone-go
func init() {
	raymond.RegisterHelpers(funcs)
}