🐛 fix third-party template loading

This commit is contained in:
naiba 2023-11-29 09:42:51 +08:00
parent efa9a30a3a
commit 6a25f39e36

View File

@ -4,7 +4,9 @@ import (
"fmt" "fmt"
"html/template" "html/template"
"io/fs" "io/fs"
"log"
"net/http" "net/http"
"os"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
@ -16,7 +18,6 @@ import (
"github.com/nicksnyder/go-i18n/v2/i18n" "github.com/nicksnyder/go-i18n/v2/i18n"
"github.com/naiba/nezha/pkg/mygin" "github.com/naiba/nezha/pkg/mygin"
"github.com/naiba/nezha/pkg/utils"
"github.com/naiba/nezha/resource" "github.com/naiba/nezha/resource"
"github.com/naiba/nezha/service/singleton" "github.com/naiba/nezha/service/singleton"
) )
@ -30,12 +31,7 @@ func ServeWeb(port uint) *http.Server {
if err != nil { if err != nil {
panic(err) panic(err)
} }
if utils.IsFileExists("resource/template") { tmpl = loadThirdPartyTemplates(tmpl)
tmpl, err = tmpl.ParseGlob("resource/template/**/*.html")
if err != nil {
panic(err)
}
}
r.SetHTMLTemplate(tmpl) r.SetHTMLTemplate(tmpl)
if singleton.Conf.Debug { if singleton.Conf.Debug {
gin.SetMode(gin.DebugMode) gin.SetMode(gin.DebugMode)
@ -87,6 +83,28 @@ func routers(r *gin.Engine) {
} }
} }
func loadThirdPartyTemplates(tmpl *template.Template) *template.Template {
var ret = tmpl
themes, err := os.ReadDir("resource/template")
if err != nil {
log.Printf("NEZHA>> Error reading themes folder: %v", err)
return ret
}
for _, theme := range themes {
if !theme.IsDir() {
continue
}
// load templates
t, err := ret.ParseGlob(fmt.Sprintf("resource/template/%s/*.html", theme.Name()))
if err != nil {
log.Printf("NEZHA>> Error parsing templates %s error: %v", theme.Name(), err)
continue
}
ret = t
}
return ret
}
var funcMap = template.FuncMap{ var funcMap = template.FuncMap{
"tr": func(id string, dataAndCount ...interface{}) string { "tr": func(id string, dataAndCount ...interface{}) string {
conf := i18n.LocalizeConfig{ conf := i18n.LocalizeConfig{