-
Notifications
You must be signed in to change notification settings - Fork 3
/
template.go
68 lines (54 loc) · 1.28 KB
/
template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package gin
import (
"html/template"
"os"
"path/filepath"
"github.com/gin-gonic/gin/render"
"github.com/goravel/framework/support"
"github.com/goravel/framework/support/file"
)
type Delims struct {
Left string
Right string
}
type RenderOptions struct {
Delims *Delims
FuncMap template.FuncMap
}
func NewTemplate(options RenderOptions) (*render.HTMLProduction, error) {
instance := template.New("")
if options.Delims != nil {
instance.Delims(options.Delims.Left, options.Delims.Right)
}
if options.FuncMap != nil {
instance.Funcs(options.FuncMap)
}
dir := "resources/views"
if support.RelativePath != "" {
dir = support.RelativePath + "/" + dir
}
if !file.Exists(dir) {
return nil, nil
}
var files []string
if err := filepath.Walk(dir, func(fullPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
files = append(files, fullPath)
}
return nil
}); err != nil {
return nil, err
}
if len(files) == 0 {
return nil, nil
}
tmpl := template.Must(instance.ParseFiles(files...))
return &render.HTMLProduction{Template: tmpl}, nil
}
// DefaultTemplate creates a TemplateRender instance with default options.
func DefaultTemplate() (*render.HTMLProduction, error) {
return NewTemplate(RenderOptions{})
}