gin中的多模板和模板继承的用法


1. 简单用法

package main

import (
	"github.com/gin-contrib/multitemplate"
	"github.com/gin-gonic/gin"
	"path/filepath"
)

func createMyRender() multitemplate.Renderer {
	r := multitemplate.NewRenderer()
	basePath, _ := filepath.Abs("templates")
	r.AddFromFiles("index", basePath + `\base.html`, basePath + `\index.html`)
	r.AddFromFiles("article", "templates/base.html", "templates/index.html", "templates/article.html")
	return r
}

func main() {
	router := gin.Default()
	router.HTMLRender = createMyRender()
	router.GET("/", func(c *gin.Context) {
		c.HTML(200, "index", gin.H{
			"title": "Html5 Template Engine",
		})
	})
	router.GET("/article", func(c *gin.Context) {
		c.HTML(200, "article", gin.H{
			"title": "Html5 Article Engine",
		})
	})
	router.GET("/json", func(context *gin.Context) {
		context.String(200, "OK")
	})

	router.Run()
}

2. 高级用法

package main

import (
	"github.com/gin-contrib/multitemplate"
	"github.com/gin-gonic/gin"
	"path/filepath"
)

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",
		})
	})
	router.GET("/login", func(context *gin.Context) {
		context.HTML(200, "login.html", gin.H{
			"title": "Login",
		})
	})

	router.Run()
}

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

	adminLayouts, err := filepath.Glob(templatesDir + "/layouts/base_admins.html")
	if err != nil {
		panic(err.Error())
	}
	adminInclude, err := filepath.Glob(templatesDir + "/admins/*.html")
	if err != nil {
		panic(err.Error())
	}
	// Generate our templates map from our layouts/ and articles/ directories
	for _, include := range adminInclude {
		layoutCopy := make([]string, len(adminLayouts))
		copy(layoutCopy, adminLayouts)
		files := append(layoutCopy, include)
		r.AddFromFiles(filepath.Base(include), files...)
	}

	articleLayouts, err := filepath.Glob(templatesDir + "/layouts/base_articles.html")
	if err != nil {
		panic(err.Error())
	}
	articleInclude, err := filepath.Glob(templatesDir + "/articles/*.html")
	if err != nil {
		panic(err.Error())
	}
	// Generate our templates map from our layouts/ and articles/ directories
	for _, include := range articleInclude {
		layoutCopy := make([]string, len(articleLayouts))
		copy(layoutCopy, articleLayouts)
		files := append(layoutCopy, include)
		r.AddFromFiles(filepath.Base(include), files...)
	}

	return r
}

项目结构

gin