diff --git a/README.md b/README.md index 72ac99bd..03327110 100644 --- a/README.md +++ b/README.md @@ -829,13 +829,17 @@ func main() { ### HTML rendering -Using LoadHTMLGlob() or LoadHTMLFiles() +Using LoadHTMLGlob(), LoadHTMLFiles() or LoadHTMLFilesRecursively ```go func main() { router := gin.Default() router.LoadHTMLGlob("templates/*") //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html") + + // load recursively all .html in "public" folder + //router.LoadHTMLFilesRecursively("public", []string{".html"}) + router.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", gin.H{ "title": "Main website", diff --git a/gin.go b/gin.go index 4205eff0..32277285 100644 --- a/gin.go +++ b/gin.go @@ -10,6 +10,9 @@ import ( "net/http" "os" "sync" + "strings" + "sort" + "path/filepath" "github.com/gin-gonic/gin/render" ) @@ -194,6 +197,26 @@ func (engine *Engine) LoadHTMLFiles(files ...string) { engine.SetHTMLTemplate(templ) } +// LoadHTMLFilesRecursively loads recursivly a slice of HTML files mathing an extension +// and associates the result with HTML renderer. +func (engine *Engine) LoadHTMLFilesRecursively(folder string, extensionsAllowed []string) { + + files := []string{} + sort.Strings(extensionsAllowed) + + filepath.Walk(folder, func(path string, info os.FileInfo, err error) error { + extension := strings.ToLower(filepath.Ext(path)) + indexFound := sort.SearchStrings(extensionsAllowed, extension) + if indexFound < len(extensionsAllowed) && extensionsAllowed[indexFound] == extension { + files = append(files, path); + } + + return nil + }) + + engine.LoadHTMLFiles(files...) +} + // SetHTMLTemplate associate a template with HTML renderer. func (engine *Engine) SetHTMLTemplate(templ *template.Template) { if len(engine.trees) > 0 {