gf/os/gview/gview_doparse.go

371 lines
11 KiB
Go
Raw Normal View History

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gview
import (
"bytes"
"errors"
"fmt"
2019-10-31 23:37:33 +08:00
"github.com/gogf/gf/encoding/ghash"
"github.com/gogf/gf/internal/intlog"
"github.com/gogf/gf/os/gfcache"
"github.com/gogf/gf/os/gfsnotify"
"github.com/gogf/gf/os/gmlock"
2019-12-17 21:06:34 +08:00
"github.com/gogf/gf/text/gstr"
2019-10-31 23:37:33 +08:00
"github.com/gogf/gf/util/gconv"
2019-12-26 11:03:59 +08:00
htmltpl "html/template"
2019-10-31 23:37:33 +08:00
"strconv"
2019-08-16 00:29:14 +08:00
"strings"
2019-12-26 11:03:59 +08:00
texttpl "text/template"
2019-07-29 21:01:19 +08:00
2019-08-16 00:29:14 +08:00
"github.com/gogf/gf/os/gres"
2019-07-29 21:01:19 +08:00
"github.com/gogf/gf/container/gmap"
"github.com/gogf/gf/os/gfile"
"github.com/gogf/gf/os/glog"
"github.com/gogf/gf/os/gspath"
)
2019-06-05 21:58:27 +08:00
const (
// Template name for content parsing.
2019-12-10 21:14:15 +08:00
gCONTENT_TEMPLATE_NAME = "TemplateContent"
2019-06-05 21:58:27 +08:00
)
2019-12-26 11:03:59 +08:00
// fileCacheItem is the cache item for template file.
type fileCacheItem struct {
path string
folder string
content string
}
var (
// Templates cache map for template folder.
2019-12-10 21:14:15 +08:00
// Note that there's no expiring logic for this map.
templates = gmap.NewStrAnyMap(true)
// Try-folders for resource template file searching.
resourceTryFolders = []string{"template/", "template", "/template", "/template/"}
)
// Parse parses given template file <file> with given template variables <params>
// and returns the parsed template content.
2019-10-31 23:37:33 +08:00
func (view *View) Parse(file string, params ...Params) (result string, err error) {
2019-12-26 11:03:59 +08:00
var tpl interface{}
// It caches the file, folder and its content to enhance performance.
2019-10-31 23:37:33 +08:00
r := view.fileCacheMap.GetOrSetFuncLock(file, func() interface{} {
var path, folder, content string
2019-10-31 23:37:33 +08:00
var resource *gres.File
// Searching the absolute file path for <file>.
path, folder, resource, err = view.searchFile(file)
if err != nil {
return nil
}
if resource != nil {
content = gconv.UnsafeBytesToStr(resource.Content())
} else {
content = gfcache.GetContents(path)
}
2019-10-31 23:37:33 +08:00
// Monitor template files changes using fsnotify asynchronously.
if resource == nil {
if _, err := gfsnotify.AddOnce("gview.Parse:"+folder, folder, func(event *gfsnotify.Event) {
// CLEAR THEM ALL.
view.fileCacheMap.Clear()
templates.Clear()
gfsnotify.Exit()
}); err != nil {
intlog.Error(err)
}
2019-08-16 00:29:14 +08:00
}
return &fileCacheItem{
path: path,
folder: folder,
content: content,
}
})
2019-10-31 23:37:33 +08:00
if r == nil {
return
}
item := r.(*fileCacheItem)
2019-12-08 22:55:32 +08:00
// It's not necessary continuing parsing if template content is empty.
if item.content == "" {
return "", nil
}
// Get the template object instance for <folder>.
2019-12-10 21:14:15 +08:00
tpl, err = view.getTemplate(item.path, item.folder, fmt.Sprintf(`*%s`, gfile.Ext(item.path)))
if err != nil {
return "", err
}
// Using memory lock to ensure concurrent safety for template parsing.
2019-12-10 21:14:15 +08:00
gmlock.LockFunc("gview.Parse:"+item.path, func() {
2019-12-26 11:03:59 +08:00
if view.config.AutoEncode {
tpl, err = tpl.(*htmltpl.Template).Parse(item.content)
} else {
tpl, err = tpl.(*texttpl.Template).Parse(item.content)
}
})
// Note that the template variable assignment cannot change the value
// of the existing <params> or view.data because both variables are pointers.
2019-10-31 23:37:33 +08:00
// It needs to merge the values of the two maps into a new map.
var variables map[string]interface{}
length := len(view.data)
if len(params) > 0 {
length += len(params[0])
}
if length > 0 {
variables = make(map[string]interface{}, length)
}
if len(view.data) > 0 {
if len(params) > 0 {
2019-10-31 23:37:33 +08:00
if variables == nil {
variables = make(map[string]interface{})
}
for k, v := range params[0] {
variables[k] = v
}
for k, v := range view.data {
variables[k] = v
}
} else {
variables = view.data
}
} else {
if len(params) > 0 {
variables = params[0]
}
}
buffer := bytes.NewBuffer(nil)
2019-12-26 11:03:59 +08:00
if view.config.AutoEncode {
if err := tpl.(*htmltpl.Template).Execute(buffer, variables); err != nil {
return "", err
}
} else {
if err := tpl.(*texttpl.Template).Execute(buffer, variables); err != nil {
return "", err
}
}
2019-12-26 11:03:59 +08:00
2019-10-31 23:37:33 +08:00
// TODO any graceful plan to replace "<no value>"?
2019-12-17 21:06:34 +08:00
result = gstr.Replace(buffer.String(), "<no value>", "")
result = view.i18nTranslate(result, variables)
return result, nil
}
// ParseDefault parses the default template file with params.
func (view *View) ParseDefault(params ...Params) (result string, err error) {
return view.Parse(view.defaultFile, params...)
}
// ParseContent parses given template content <content> with template variables <params>
// and returns the parsed content in []byte.
2019-06-19 09:06:52 +08:00
func (view *View) ParseContent(content string, params ...Params) (string, error) {
2019-12-08 22:55:32 +08:00
// It's not necessary continuing parsing if template content is empty.
if content == "" {
return "", nil
}
2019-06-05 21:58:27 +08:00
err := (error)(nil)
key := fmt.Sprintf("%s_%v", gCONTENT_TEMPLATE_NAME, view.delimiters)
tpl := templates.GetOrSetFuncLock(key, func() interface{} {
2019-12-26 11:03:59 +08:00
if view.config.AutoEncode {
return htmltpl.New(gCONTENT_TEMPLATE_NAME).Delims(view.delimiters[0], view.delimiters[1]).Funcs(view.funcMap)
}
return texttpl.New(gCONTENT_TEMPLATE_NAME).Delims(view.delimiters[0], view.delimiters[1]).Funcs(view.funcMap)
})
2019-06-05 21:58:27 +08:00
// Using memory lock to ensure concurrent safety for content parsing.
2019-10-31 23:37:33 +08:00
hash := strconv.FormatUint(ghash.DJBHash64([]byte(content)), 10)
gmlock.LockFunc("gview.ParseContent:"+hash, func() {
2019-12-26 11:03:59 +08:00
if view.config.AutoEncode {
tpl, err = tpl.(*htmltpl.Template).Parse(content)
} else {
tpl, err = tpl.(*texttpl.Template).Parse(content)
}
2019-06-05 21:58:27 +08:00
})
if err != nil {
return "", err
}
// Note that the template variable assignment cannot change the value
// of the existing <params> or view.data because both variables are pointers.
2019-10-31 23:37:33 +08:00
// It needs to merge the values of the two maps into a new map.
var variables map[string]interface{}
length := len(view.data)
if len(params) > 0 {
length += len(params[0])
}
if length > 0 {
variables = make(map[string]interface{}, length)
}
if len(view.data) > 0 {
if len(params) > 0 {
2019-10-31 23:37:33 +08:00
if variables == nil {
variables = make(map[string]interface{})
}
for k, v := range params[0] {
variables[k] = v
}
for k, v := range view.data {
variables[k] = v
}
} else {
variables = view.data
}
} else {
if len(params) > 0 {
variables = params[0]
}
}
buffer := bytes.NewBuffer(nil)
2019-12-26 11:03:59 +08:00
if view.config.AutoEncode {
if err := tpl.(*htmltpl.Template).Execute(buffer, variables); err != nil {
return "", err
}
} else {
if err := tpl.(*texttpl.Template).Execute(buffer, variables); err != nil {
return "", err
}
}
2019-10-31 23:37:33 +08:00
// TODO any graceful plan to replace "<no value>"?
2019-12-17 21:06:34 +08:00
result := gstr.Replace(buffer.String(), "<no value>", "")
result = view.i18nTranslate(result, variables)
return result, nil
}
2019-10-31 23:37:33 +08:00
2019-12-10 21:14:15 +08:00
// getTemplate returns the template object associated with given template file <path>.
2019-10-31 23:37:33 +08:00
// It uses template cache to enhance performance, that is, it will return the same template object
// with the same given <path>. It will also automatically refresh the template cache
2019-10-31 23:37:33 +08:00
// if the template files under <path> changes (recursively).
2019-12-26 11:03:59 +08:00
func (view *View) getTemplate(filePath, folderPath, pattern string) (tpl interface{}, err error) {
2019-12-10 21:14:15 +08:00
// Key for template cache.
key := fmt.Sprintf("%s_%v", filePath, view.delimiters)
result := templates.GetOrSetFuncLock(key, func() interface{} {
2019-12-26 11:03:59 +08:00
// Do not use <key> but the <filePath> as the parameter <name> for function New,
// because when error occurs the <name> will be printed out for error locating.
if view.config.AutoEncode {
tpl = htmltpl.New(filePath).Delims(view.delimiters[0], view.delimiters[1]).Funcs(view.funcMap)
} else {
tpl = texttpl.New(filePath).Delims(view.delimiters[0], view.delimiters[1]).Funcs(view.funcMap)
}
2019-10-31 23:37:33 +08:00
// Firstly checking the resource manager.
if !gres.IsEmpty() {
2019-12-10 21:14:15 +08:00
if files := gres.ScanDirFile(folderPath, pattern, true); len(files) > 0 {
2019-10-31 23:37:33 +08:00
var err error
for _, v := range files {
2019-12-26 11:03:59 +08:00
if view.config.AutoEncode {
_, err = tpl.(*htmltpl.Template).New(v.FileInfo().Name()).Parse(string(v.Content()))
if err != nil {
glog.Error(err)
}
} else {
_, err = tpl.(*texttpl.Template).New(v.FileInfo().Name()).Parse(string(v.Content()))
if err != nil {
glog.Error(err)
}
2019-10-31 23:37:33 +08:00
}
}
return tpl
}
}
// Secondly checking the file system.
var files []string
2019-12-10 21:14:15 +08:00
files, err = gfile.ScanDir(folderPath, pattern, true)
2019-10-31 23:37:33 +08:00
if err != nil {
return nil
}
2019-12-26 11:03:59 +08:00
if view.config.AutoEncode {
if tpl, err = tpl.(*htmltpl.Template).ParseFiles(files...); err != nil {
return nil
}
} else {
if tpl, err = tpl.(*texttpl.Template).ParseFiles(files...); err != nil {
return nil
}
2019-10-31 23:37:33 +08:00
}
return tpl
})
if result != nil {
2019-12-26 11:03:59 +08:00
return result, nil
2019-10-31 23:37:33 +08:00
}
return
}
// searchFile returns the found absolute path for <file> and its template folder path.
2019-12-10 21:14:15 +08:00
// Note that, the returned <folder> is the template folder path, but not the folder of
// the returned template file <path>.
2019-10-31 23:37:33 +08:00
func (view *View) searchFile(file string) (path string, folder string, resource *gres.File, err error) {
// Firstly checking the resource manager.
if !gres.IsEmpty() {
2019-12-10 21:14:15 +08:00
// Try folders.
for _, folderPath := range resourceTryFolders {
if resource = gres.Get(folderPath + file); resource != nil {
2019-10-31 23:37:33 +08:00
path = resource.Name()
2019-12-10 21:14:15 +08:00
folder = folderPath
2019-10-31 23:37:33 +08:00
return
}
}
2019-12-10 21:14:15 +08:00
// Search folders.
2019-10-31 23:37:33 +08:00
view.paths.RLockFunc(func(array []string) {
for _, v := range array {
v = strings.TrimRight(v, "/"+gfile.Separator)
if resource = gres.Get(v + "/" + file); resource != nil {
path = resource.Name()
folder = v
break
}
if resource = gres.Get(v + "/template/" + file); resource != nil {
path = resource.Name()
folder = v + "/template"
break
}
}
})
}
// Secondly checking the file system.
if path == "" {
view.paths.RLockFunc(func(array []string) {
2019-12-10 21:14:15 +08:00
for _, folderPath := range array {
folderPath = strings.TrimRight(folderPath, gfile.Separator)
if path, _ = gspath.Search(folderPath, file); path != "" {
folder = folderPath
2019-10-31 23:37:33 +08:00
break
}
2019-12-10 21:14:15 +08:00
if path, _ = gspath.Search(folderPath+gfile.Separator+"template", file); path != "" {
folder = folderPath + gfile.Separator + "template"
2019-10-31 23:37:33 +08:00
break
}
}
})
}
// Error checking.
if path == "" {
buffer := bytes.NewBuffer(nil)
if view.paths.Len() > 0 {
buffer.WriteString(fmt.Sprintf("[gview] cannot find template file \"%s\" in following paths:", file))
view.paths.RLockFunc(func(array []string) {
index := 1
2019-12-10 21:14:15 +08:00
for _, folderPath := range array {
folderPath = strings.TrimRight(folderPath, "/")
if folderPath == "" {
folderPath = "/"
2019-10-31 23:37:33 +08:00
}
2019-12-10 21:14:15 +08:00
buffer.WriteString(fmt.Sprintf("\n%d. %s", index, folderPath))
2019-10-31 23:37:33 +08:00
index++
2019-12-10 21:14:15 +08:00
buffer.WriteString(fmt.Sprintf("\n%d. %s", index, strings.TrimRight(folderPath, "/")+gfile.Separator+"template"))
2019-10-31 23:37:33 +08:00
index++
}
})
} else {
buffer.WriteString(fmt.Sprintf("[gview] cannot find template file \"%s\" with no path set/add", file))
}
if errorPrint() {
glog.Error(buffer.String())
}
err = errors.New(fmt.Sprintf(`template file "%s" not found`, file))
}
return
}