This commit is contained in:
2025-12-27 21:59:58 +08:00
parent 22f800726c
commit 530f1d833d
135 changed files with 1644 additions and 198661 deletions

View File

@@ -2,8 +2,13 @@ package tmpl
import (
"encoding/json"
"fmt"
"html/template"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/gin-gonic/gin"
)
@@ -22,7 +27,47 @@ func New(app *gin.Engine) {
}
app.SetFuncMap(funcMap)
app.LoadHTMLGlob("./res/templates/*")
// 加载所有HTML模板
templ := loadTemplates("./res/templates")
app.SetHTMLTemplate(templ)
}
// loadTemplates 加载所有HTML模板
func loadTemplates(templatesDir string) *template.Template {
tmpl := template.New("")
// 首先加载组件和布局模板(.tpl文件
err := filepath.Walk(templatesDir, func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
// 加载.tpl文件组件和布局
if !info.IsDir() && strings.HasSuffix(path, ".html") {
content, err := os.ReadFile(path)
if err != nil {
return err
}
// 使用相对路径作为模板名,保持目录结构
relPath, _ := filepath.Rel(templatesDir, path)
templateName := strings.ReplaceAll(relPath, "\\", "/")
// 如果不是 components 或 layouts 目录中的文件,且包含 {{define "content"}}
// 则将其重命名为唯一的 content 名称(基于文件名)
contentStr := string(content)
_, err = tmpl.New(templateName).Parse(contentStr)
if err != nil {
return fmt.Errorf("解析模板 %s 失败: %v", path, err)
}
fmt.Printf("已加载组件/布局模板: %s\n", templateName)
}
return nil
})
if err != nil {
log.Fatalf("加载组件模板失败: %v", err)
}
return tmpl
}
func TestFunc(in string) string {