forked from gin-contrib/multitemplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.go
51 lines (43 loc) · 1.09 KB
/
example.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"log"
"path/filepath"
"github.com/gin-contrib/multitemplate"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.HTMLRender = loadTemplates("./templates")
router.GET("/", func(c *gin.Context) {
c.HTML(200, "index.html", gin.H{
"title": "Welcome!",
})
})
router.GET("/article", func(c *gin.Context) {
c.HTML(200, "article.html", gin.H{
"title": "Html5 Article Engine",
})
})
if err := router.Run(":8080"); err != nil {
log.Fatal(err)
}
}
func loadTemplates(templatesDir string) multitemplate.Renderer {
r := multitemplate.NewRenderer()
layouts, err := filepath.Glob(templatesDir + "/layouts/*.html")
if err != nil {
panic(err.Error())
}
includes, err := filepath.Glob(templatesDir + "/includes/*.html")
if err != nil {
panic(err.Error())
}
// Generate our templates map from our layouts/ and includes/ directories
for _, include := range includes {
layoutCopy := make([]string, len(layouts))
copy(layoutCopy, layouts)
files := append(layoutCopy, include)
r.AddFromFiles(filepath.Base(include), files...)
}
return r
}