Skip to content

Commit

Permalink
Merge pull request #21 from caitinggui/master
Browse files Browse the repository at this point in the history
Add multiple layouts templates example source code
  • Loading branch information
thinkerou committed Jan 18, 2019
2 parents 13b7778 + 0620287 commit 542ef92
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 0 deletions.
66 changes: 66 additions & 0 deletions example/multibase/example.go
@@ -0,0 +1,66 @@
package main

import (
"path/filepath"

"github.com/gin-contrib/multitemplate"
"github.com/gin-gonic/gin"
)

func main() {
router := gin.Default()
router.HTMLRender = loadTemplates("./templates")
router.GET("/admin", func(c *gin.Context) {
c.HTML(200, "admin.html", gin.H{
"title": "Welcome!",
})
})
router.GET("/article", func(c *gin.Context) {
c.HTML(200, "article.html", gin.H{
"title": "Html5 Article Engine",
})
})

router.Run(":8080")
}

func loadTemplates(templatesDir string) multitemplate.Renderer {
r := multitemplate.NewRenderer()

articleLayouts, err := filepath.Glob(templatesDir + "/layouts/article-base.html")
if err != nil {
panic(err.Error())
}

articles, err := filepath.Glob(templatesDir + "/articles/*.html")
if err != nil {
panic(err.Error())
}

// Generate our templates map from our articleLayouts/ and articles/ directories
for _, article := range articles {
layoutCopy := make([]string, len(articleLayouts))
copy(layoutCopy, articleLayouts)
files := append(layoutCopy, article)
r.AddFromFiles(filepath.Base(article), files...)
}

adminLayouts, err := filepath.Glob(templatesDir + "/layouts/admin-base.html")
if err != nil {
panic(err.Error())
}

admins, err := filepath.Glob(templatesDir + "/admins/*.html")
if err != nil {
panic(err.Error())
}

// Generate our templates map from our adminLayouts/ and admins/ directories
for _, admin := range admins {
layoutCopy := make([]string, len(adminLayouts))
copy(layoutCopy, adminLayouts)
files := append(layoutCopy, admin)
r.AddFromFiles(filepath.Base(admin), files...)
}
return r
}
1 change: 1 addition & 0 deletions example/multibase/templates/admins/admin.html
@@ -0,0 +1 @@
{{define "content"}}Hi, this is admin.html{{end}}
1 change: 1 addition & 0 deletions example/multibase/templates/articles/article.html
@@ -0,0 +1 @@
{{define "content"}}Hi, this is article template{{end}}
3 changes: 3 additions & 0 deletions example/multibase/templates/layouts/admin-base.html
@@ -0,0 +1,3 @@
Admin Title: {{ .title }}

index template: {{template "content" .}}
3 changes: 3 additions & 0 deletions example/multibase/templates/layouts/article-base.html
@@ -0,0 +1,3 @@
Article Title: {{ .title }}

index template: {{template "content" .}}

0 comments on commit 542ef92

Please sign in to comment.