龙空技术网

Golang Web - gin加载多个模板目录

linux运维菜 182

前言:

目前各位老铁们对“模板列表css”大致比较讲究,朋友们都想要了解一些“模板列表css”的相关文章。那么小编在网络上汇集了一些有关“模板列表css””的相关文章,希望你们能喜欢,咱们一起来学习一下吧!

简介

gin默认是使用text/template,只支持加载一个路径下的模板,而且只取最后的名字,所以有相同文件名字的文件,就有可能加载不到了。

gin.LoadHTMLGlob,这个是加载模板目录的,查找模板文件的时候,调用的是filepath.Glob(pattern),patter 设置 "templates/**/*",在Golang之前的版本是可以匹配到目录和文件,但是在现在的稳定版本,跟"tmplates/*/*"的效果是一样的。因此需要加载多级目录就需要使用multitemplate这个库。

代码

package routerimport (	"dbops/apps/users"	"fmt"	"io/ioutil"	"os"	"path"	"path/filepath"	"strings"	"github.com/gin-contrib/multitemplate"	"github.com/gin-gonic/gin")func getFilelist(path string, stuffix string) (files []string) {	// 遍历目录	filepath.Walk(path, func(path string, f os.FileInfo, err error) error {		if f == nil {			return err		}		if f.IsDir() {			return nil		}		// 将模板后缀的文件放到列表		if strings.HasSuffix(path, stuffix) {			files = append(files, path)		}		return nil	})	return}// LoadTemplateFiles 加载模板func LoadTemplateFiles(templateDir, stuffix string) multitemplate.Renderer {	r := multitemplate.NewRenderer()	rd, _ := ioutil.ReadDir(templateDir)	for _, fi := range rd {		if fi.IsDir() {			// 如果是目录			for _, f := range getFilelist(path.Join(templateDir, fi.Name()), stuffix) {				// 添加到模板的时候,去掉跟路径				r.AddFromFiles(f[len(templateDir)+1:], f)			}		} else {			if strings.HasSuffix(fi.Name(), stuffix) {				// 如果再根目录底下的文件直接添加				r.AddFromFiles(fi.Name(), path.Join(templateDir, fi.Name()))			}		}	}	fmt.Println(r)	return r}// Run run Serverfunc Run() {	engine := gin.Default()	// HTMLRender加载模板	engine.HTMLRender = LoadTemplateFiles("templates", ".html")	engine.Static("static", "static")	engine.GET("/login", func(c *gin.Context){		c.HTML(http.StatusOK,"users/login.html",gin.H{})		})	engine.GET("/", func(c *gin.Context){		c.HTML(http.StatusOK,"dashboard/index.html",gin.H{})		})	engine.Run()}

标签: #模板列表css