gin如何加载不同层级目录的html

gin如何加载不同层级目录的html

在 github.com/gin-gonic/gin 新建 LoadHTMLFolder.go

package gin

import (
	"html/template"
	"path/filepath"
	"strings"
	"os"
	"io/fs"
	"fmt"
)

// LoadHTMLFolder loads HTML files identified by glob pattern
// and associates the result with HTML renderer.
func (engine *Engine) LoadHTMLFolder(path string) {
	templ := template.Must(parseHtml(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap),path))
	engine.SetHTMLTemplate(templ)
}

func parseHtml(t *template.Template, folder string) (*template.Template, error) {
	// 获取模板文件加载
	tplFiles := map[string]string{}
	filepath.WalkDir(folder, func(path string, d fs.DirEntry, err error) error {
		if !d.IsDir() && strings.HasSuffix(d.Name(), ".html") {
			name := strings.TrimPrefix(path,folder)
			name =  strings.TrimPrefix(strings.ReplaceAll(name,"\\","/"),"/")
			tplFiles[name] = path
		}
		return nil
	})
	return parseFiles(t, readFileOS, tplFiles)
}

// parseFiles is the helper for the method and function. If the argument
// template is nil, it is created from the first file.
func parseFiles(t *template.Template, readFile func(string) (string, []byte, error), filenames map[string]string) (*template.Template, error) {
	if len(filenames) == 0 {
		// Not really a problem, but be consistent.
		return nil, fmt.Errorf("html/template: no files named in call to ParseFiles")
	}
	// for _, filename := range filenames
	for name, filename := range filenames {
		// 默认是 _, b, err := readFile(filename)
		_, b, err := readFile(filename)
		if err != nil {
			return nil, err
		}
		s := string(b)
		// First template becomes return value if not already defined,
		// and we use that one for subsequent New calls to associate
		// all the templates together. Also, if this file has the same name
		// as t, this file becomes the contents of t, so
		//  t, err := New(name).Funcs(xxx).ParseFiles(name)
		// works. Otherwise we create a new template associated with t.
		var tmpl *template.Template
		if t == nil {
			t = template.New(name)
		}
		if name == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(name)
		}
		_, err = tmpl.Parse(s)
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}

func readFileOS(file string) (name string, b []byte, err error) {
	name = filepath.Base(file)
	b, err = os.ReadFile(file)
	return
}

目录结构

gin.LoadHTMLFolder("templates")

c.HTML(http.StatusOK, "index.html", gin.H{})

c.HTML(http.StatusOK, "user/user.html", gin.H{})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值