Skip to content

Instantly share code, notes, and snippets.

@henryhamon
Created December 31, 2017 11:50
Show Gist options
  • Save henryhamon/94d468c8c399d954b791c1d683b1d530 to your computer and use it in GitHub Desktop.
Save henryhamon/94d468c8c399d954b791c1d683b1d530 to your computer and use it in GitHub Desktop.
// I just write a finder to find templates,
func TemplatesFinder(engine *gin.Engine, pathOfRoot, templateDirName string) {
dir := gin.Dir(pathOfRoot, true)
file, err := dir.Open(templateDirName)
util.PanicError(err)
defer file.Close()
dirs, err := file.Readdir(10)
util.PanicError(err)
templatePages := make([]string, 0, 10)
dirStack := collections.NewStack(10)
for _, v := range dirs {
if v.IsDir() {
fileNode := v.Name()
dirStack.Push(fileNode)
} else {
templatePages = append(templatePages, templateDirName + "/" + v.Name())
}
}
// range every dir, and find sub dirs
for {
if rootDir, ok := dirStack.Pop(); ok {
tmpDir := fmt.Sprint(rootDir)
dir := gin.Dir(templateDirName + "/" + tmpDir, true)
file, err := dir.Open(".")
util.PanicError(err)
defer file.Close()
dirs, err = file.Readdir(10)
for _, v := range dirs {
path := tmpDir + "/" + v.Name()
if v.IsDir() {
dirStack.Push(tmpDir)
} else {
templatePages = append(templatePages, templateDirName + "/" + path)
}
}
} else {
log.Logger.Debug("has no elements....")
break
}
}
temp, err := template.ParseGlob("templates/*\\.tmpl")
util.PanicError(err)
for _, v := range temp.Templates() {
log.Logger.Debug("templates: %v", v.Name())
}
log.Logger.Debug("all template pages: %v", templatePages)
engine.LoadHTMLFiles(templatePages...)
}
// and u can use like this just assume your templates are in templates directory, and main file is in the root of project:
g = gin.New()
TemplatesFinder(g, ".", "templates")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment