package node import ( "os" "strings" "text/template" log "github.com/sirupsen/logrus" ) const ( // Common templates CommonTplDir = "common" // Reusable components ComponentsTplDir = "components" // Something like component of components MetaTplDir = "meta" // Main pages ViewsTplDir = "views" ) func (s *ssr) tplDir(name string) string { return strings.Join([]string{s.templatesDir, name}, string(os.PathSeparator)) } func (s *ssr) readTplDir(name string) ([]string, error) { var paths []string dir, err := os.ReadDir(s.templatesDir + string(os.PathSeparator) + name) if err != nil { return nil, err } for _, entry := range dir { if strings.HasSuffix(entry.Name(), ".html") { paths = append(paths, strings.Join( []string{s.templatesDir, name, entry.Name()}, string(os.PathSeparator))) } } return paths, nil } func (s *ssr) tplsPaths() ([]string, error) { var paths []string // Read common dir commonTpls, err := s.readTplDir(CommonTplDir) if err != nil { return nil, err } paths = append(paths, commonTpls...) // Read components dir compTpls, err := s.readTplDir(ComponentsTplDir) if err != nil { return nil, err } paths = append(paths, compTpls...) // Read meta dir metaTpls, err := s.readTplDir(MetaTplDir) if err != nil { return nil, err } paths = append(paths, metaTpls...) return paths, nil } func (s *ssr) componentsForTemplate(name string) []string { paths := []string{s.tplDir(ViewsTplDir) + string(os.PathSeparator) + name + ".html"} tpls, err := s.tplsPaths() if err != nil { log.Error(err) return paths } return append(paths, tpls...) } func (s *ssr) templatePath(name string) string { return s.templatesDir + string(os.PathSeparator) + name } func (s *ssr) getTemplate(name string) (*template.Template, error) { t := template.New(name + ".html") tpl, err := t.ParseFiles(s.componentsForTemplate(name)...) if err != nil { return nil, err } return tpl, nil }