1、multitemplate渲染方法
func render(template, bases string, includes []string) multitemplate.Renderer {
/*
template : 模板目录
bases : 被继承的目录
includes []string : 渲染的目录列表
返回结果是 multitemplate.Renderer
通过app.HTMLRender = render("template", "bases", []string{"admin", "index"})加载
*/
var r = multitemplate.NewRenderer()
// 拼接被进程的目录,*是通配符,匹配所有文件,也可以写成*.html
// template/bases/*
var bases_path = fmt.Sprintf("%v/%v/*", template, bases)
// 循环 渲染的目录列表 ,
for _, include := range includes {
// 获取被继承的目录的所有文件的相对路径
baseFiles, _ := filepath.Glob(bases_path)
// 拼接渲染的目录的路径名
var includePath = fmt.Sprintf("%v/%v/*", template, include)
// 获取渲染目录的所有文件的绝对路径名
includeFiles, _ := filepath.Glob(includePath)
// 循环渲染目录的每个文件
for _, includeFile := range includeFiles {
// 将渲染目录的每个文件和被继承目录的所有文件拼接,形成切片
files := append([]string{includeFile}, baseFiles...)
// 拼接渲染的名称,在c.html中调用的名字
// 如template/admin/index.html,将拼接成admin_index.html
// 如template/index/index.html,将拼接成index_index.html
name := include + "_" + filepath.Base(includeFile)
// 使用AddFromFiles方法,渲染需要的文件
r.AddFromFiles(name, files...)
}
}
return r
}
2、主程序
package main
import (
"fmt"
"github.com/gin-contrib/multitemplate"
"github.com/gin-gonic/gin"
"log"
"path/filepath"
"project_ask/view"
)
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
app := gin.Default()
app.HTMLRender = render("template", "bases", []string{"admin", "index"})
view.Static(app)
router(app)
_ = app.Run(":80")
}
3、路由
package main
import (
"github.com/gin-gonic/gin"
"project_ask/controller"
)
func router(app *gin.Engine) {
app.GET("/admin", controller.Index{}.AdminIndex)
app.GET("/index", controller.Index{}.IndexIndex)
}
4、控制器
package controller
import (
"github.com/gin-gonic/gin"
)
type Index struct{}
func (Index) IndexIndex(c *gin.Context) {
c.HTML(200, "index_index.html", nil)
}
func (Index) AdminIndex(c *gin.Context) {
c.HTML(200, "admin_index.html", nil)
}
5、html
本文暂时没有评论,来添加一个吧(●'◡'●)