/
doc.go
155 lines (125 loc) · 4.11 KB
/
doc.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package webapp
// 26.04.15 11:47
// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com), www.webjinn.ru
import (
"bytes"
html "html/template"
"log"
"github.com/dblokhin/typo"
"github.com/kennygrant/sanitize"
)
var (
// Кэш template'ов для единоразового чтения с диска. TODO: задействовать.
tpls map[string]*html.Template
)
// AbstractPage - структура задающая общие поля для шаблонов всех веб-страниц
type AbstractPage map[string]interface{}
// Основные рекомендуемые поля:
// Host string
// MetaTitle string
// MetaDescription string
// MetaAuthor string
// MetaCopyright string
// MetaKeywords string
// MetaOgImage string
// MetaOgTitle string
// MetaOgDescription string
// ContactEmail string
// ContactPhone string
// Clone возвращает новый экземляр AbstractPage c наследованными полями и значениями
func (page AbstractPage) Clone(tplName string) AbstractPage {
doc := make(AbstractPage)
for k, v := range page {
doc[k] = v
}
doc["__tpl"] = tplName
return doc
}
// Into возвращает новый экземляр AbstractPage c наследованными полями и значениями,
// при этом вписывается родителю в поле field
func (page AbstractPage) Into(field, tplName string) AbstractPage {
doc := make(AbstractPage)
for k, v := range page {
doc[k] = v
}
doc["__tpl"] = tplName
page[field] = doc
return doc
}
// Compile return page formatted with template from tpls/%d.tpl
func (page AbstractPage) Compile() string {
var data bytes.Buffer
for k, v := range page {
switch val := v.(type) {
case AbstractPage: {
page[k] = html.HTML(val.Compile())
}
case func()string: {
page[k] = val()
}
}
}
// Директива загрузки модулей динамичная (ctx записан в doc["Ctx"])
getTpl(page["__tpl"].(string)).Execute(&data, page)
return data.String()
}
// Tpls return template Name (load from cache/fs)
func getTpl(Name string) *html.Template {
defer func() {
if err := recover(); err != nil {
log.Println(err)
}
}()
res, ok := tpls[Name]
if !ok {
res = loadTemplate(Name)
}
return res
}
// loadTemplate load template from tpls/%s.tpl
func loadTemplate(Name string) *html.Template {
funcMap := html.FuncMap{
"html": func(val interface{}) html.HTML {
switch value := val.(type) {
case string: {
return html.HTML(value)
}
case html.HTML: {
return value
}
default: return html.HTML("Unsupported type for HTML pipeline")
}
},
"typo": func(val string) string {
return typo.Typo(val)
},
"striptags": func(val string) string {
return sanitize.HTML(val)
},
// TODO: в разработке
/*"mod": func(args ...interface{}) interface{} {
if len(args) == 0 {
return ""
}
name := args[0].(string)
ctx := new(context.Context)
if len(args) > 1 {
ctx = args[1].(*context.Context)
}
modules := reflect.ValueOf(modules.Get())
mod := modules.MethodByName(name)
if (mod == reflect.Value{}) {
return ""
}
inputs := make([]reflect.Value, 0)
inputs = append(inputs, reflect.ValueOf(ctx))
ret := mod.Call(inputs)
return ret[0].Interface()
},*/
}
return html.Must(html.New("*").Funcs(funcMap).Delims("{{%", "%}}").ParseFiles("tpls/" + Name + ".tpl"))
}
func init() {
// init Init cache of templates
tpls = make(map[string]*html.Template)
}