Add new method LoadHTMLFilesRecursively for recursively load template files in a folder

This commit is contained in:
math-nao 2018-03-22 22:14:21 +01:00
parent 65a65c2edd
commit 58752b5750
2 changed files with 28 additions and 1 deletions

View File

@ -829,13 +829,17 @@ func main() {
### HTML rendering ### HTML rendering
Using LoadHTMLGlob() or LoadHTMLFiles() Using LoadHTMLGlob(), LoadHTMLFiles() or LoadHTMLFilesRecursively
```go ```go
func main() { func main() {
router := gin.Default() router := gin.Default()
router.LoadHTMLGlob("templates/*") router.LoadHTMLGlob("templates/*")
//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html") //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) { router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{ c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "Main website", "title": "Main website",

23
gin.go
View File

@ -10,6 +10,9 @@ import (
"net/http" "net/http"
"os" "os"
"sync" "sync"
"strings"
"sort"
"path/filepath"
"github.com/gin-gonic/gin/render" "github.com/gin-gonic/gin/render"
) )
@ -194,6 +197,26 @@ func (engine *Engine) LoadHTMLFiles(files ...string) {
engine.SetHTMLTemplate(templ) 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. // SetHTMLTemplate associate a template with HTML renderer.
func (engine *Engine) SetHTMLTemplate(templ *template.Template) { func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
if len(engine.trees) > 0 { if len(engine.trees) > 0 {