Пример #1
0
func (self *Route) LoadTemplate(basePath string) error {
	if err := pongo.Initialize(); err != nil {
		return err
	}

	if err := mustache.Initialize(); err != nil {
		return err
	}

	self.basePath = basePath

	//  figure out the template path
	if self.TemplateName == `` {
		self.templatePath = path.Join(self.basePath, fmt.Sprintf("%s.%s", self.Path, strings.ToLower(self.Engine)))
	} else if strings.HasPrefix(self.TemplateName, `/`) {
		self.templatePath = self.TemplateName
	} else {
		self.templatePath = path.Join(self.basePath, fmt.Sprintf("%s.%s", self.TemplateName, strings.ToLower(self.Engine)))
	}

	//  figure out what this template's unique key will be
	self.templateKey = strings.TrimSuffix(strings.TrimPrefix(self.templatePath, path.Clean(self.basePath)+`/`), path.Ext(self.templatePath))

	//  get and instance of this template engine
	switch self.Engine {
	case `mustache`:
		self.template = mustache.New()
	case `pongo`:
		self.template = pongo.New()
	default:
		return fmt.Errorf("Unknown template engine '%s'", self.Engine)
	}

	//  attempt to stat the template file
	if _, err := os.Stat(self.templatePath); err == nil {
		self.template.SetTemplateDir(self.basePath)
	} else {
		return err
	}

	if err := self.template.Load(self.templateKey); err != nil {
		return fmt.Errorf("Error loading template '%s': %v", self.templatePath, err)
	}

	return nil
}
Пример #2
0
func (self *Server) LoadTemplates() error {
	if err := pongo.Initialize(); err != nil {
		return nil
	}

	return filepath.Walk(self.TemplatePath, func(filename string, info os.FileInfo, err error) error {
		log.Debugf("File in template path: %s (err: %v)", filename, err)

		if err == nil {
			if info.Mode().IsRegular() && !strings.HasPrefix(path.Base(filename), `_`) {
				ext := path.Ext(filename)
				key := strings.TrimSuffix(strings.TrimPrefix(filename, path.Clean(self.TemplatePath)+`/`), ext)

				if _, ok := self.Templates[key]; !ok {
					var tpl engines.ITemplate

					switch ext {
					case `.pongo`:
						tpl = pongo.New()
					default:
						return nil
					}

					tpl.SetTemplateDir(self.TemplatePath)

					log.Debugf("Load template at %s: %T: [%s] %s", filename, tpl, key, tpl.GetTemplateDir())

					if err := tpl.Load(key); err == nil {
						self.Templates[key] = tpl
					} else {
						log.Warnf("Error loading template '%s': %v", filename, err)
						return nil
					}
				} else {
					log.Warnf("Cannot load template '%s', key was already loaded", filename)
				}
			}
		}

		return nil
	})
}