mirror of https://github.com/gin-gonic/gin.git
Add new method LoadHTMLFilesRecursively for recursively load template files in a folder
This commit is contained in:
parent
65a65c2edd
commit
58752b5750
|
@ -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",
|
||||
|
|
23
gin.go
23
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 {
|
||||
|
|
Loading…
Reference in New Issue