-
Notifications
You must be signed in to change notification settings - Fork 1
/
xtemplate.go
475 lines (436 loc) · 13 KB
/
xtemplate.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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
package xcore
import (
"errors"
"fmt"
"io/ioutil"
"os"
"regexp"
"sort"
"strconv"
"strings"
)
/*
class to compile and keep a Template string
A template is a set of HTML/XML (or any other language) set of:
Comments:
%-- comments --%
Fields:
{{field}}
{{field>Subfield>Subfield}}
Language injection
##entry##
Subtemplates:
xml/html code
[[id]]
xml/html code
[[id]]
xml/html code indented
[[]]
xml/html code
[[]]
Meta elements:
??xx?? if/then/else
@@xx@@ loops
&&xx&& references
!!xx!! debug (dump)
*/
// MetaString and other consts:
// type of elements present in the template
const (
MetaString = 0 // a simple string to integrate into the code
MetaComment = 1 // Comment, ignore it
MetaLanguage = 2 // one param of the URL parameters list, index-1 based [page]/value1/value2...
MetaReference = 3 // an URL variable coming through a query ?variable=value
MetaRange = 4 // Parameter passed to the page Run by code
MetaCondition = 5 // System (site) parameter
MetaDump = 6 // Main page called parameters (into .page file)
MetaVariable = 7 // this page parameters (into .page file), same as Main page parameters if it's the external called page
MetaTemplateStart = 101 // Temporal nested box start tag
MetaTemplateEnd = 102 // Temporal nested box end tag
MetaUnused = -1 // a "not used anymore" param to be freed
)
// XTemplateParam is a parameter definition into the template
type XTemplateParam struct {
ParamType int
Data string
// children *XTemplateData
}
// XTemplateData is an Array of all the parameters into the template
type XTemplateData []XTemplateParam
// XTemplate is the plain template structure
type XTemplate struct {
Name string
Root *XTemplateData
SubTemplates map[string]*XTemplate
}
// NewXTemplate will create a new empty template
func NewXTemplate() *XTemplate {
return &XTemplate{}
}
// NewXTemplateFromFile will create a new template from a file containing the template code
func NewXTemplateFromFile(file string) (*XTemplate, error) {
t := &XTemplate{}
err := t.LoadFile(file)
if err != nil {
return nil, err
}
return t, nil
}
// NewXTemplateFromString will create a new template from a string containing the template code
func NewXTemplateFromString(data string) (*XTemplate, error) {
t := &XTemplate{}
err := t.LoadString(data)
if err != nil {
return nil, err
}
return t, nil
}
// LoadFile will load a file into the template
func (t *XTemplate) LoadFile(file string) error {
tFile, err := os.Open(file)
if err != nil {
return err
}
data, err := ioutil.ReadAll(tFile)
if err != nil {
return err
}
err = tFile.Close()
if err != nil {
return err
}
return t.LoadString(string(data))
}
// LoadString will load a string into the template
func (t *XTemplate) LoadString(data string) error {
return t.compile(data)
}
// compile will interprete the template code into objects
func (t *XTemplate) compile(data string) error {
// build, compile return result
code :=
`(?s)` + // . is multiline
// ==== COMENTS
`(%)--(.*?)--%(\n|\r|\r\n|\n\r)?` + // index based 1
// ==== LANGUAGE INJECTION
`|(#)#(.+?)##` + // index based 4
// ==== ELEMENTS
`|(&)&(.+?)&&` + // index based 6
`|(@)@(.+?)@@` + // index based 8
`|(\?)\?(.+?)\?\?` + // index based 10
`|(\!)\!(.+?)\!\!` + // index based 12
`|(\{)\{(.+?)\}\}` + // index based 14
// ==== NESTED ELEMENTS (SUB TEMPLATES)
`|\[\[(\])\](\n|\r|\r\n|\n\r)?` + // index based 16
`|(\[)\[([a-z0-9\|\.\-_]+?)\]\](\n|\r|\r\n|\n\r)?` // index based 18
codex := regexp.MustCompile(code)
indexes := codex.FindAllStringIndex(data, -1)
matches := codex.FindAllStringSubmatch(data, -1)
var compiled XTemplateData
pointer := 0
for i, x := range indexes {
if pointer != x[0] {
compiled = append(compiled, *(&XTemplateParam{ParamType: MetaString, Data: data[pointer:x[0]]}))
}
param := &XTemplateParam{}
if matches[i][1] == "%" {
param.ParamType = MetaComment // comment
param.Data = matches[i][2]
} else if matches[i][4] == "#" {
param.ParamType = MetaLanguage // Language entry
param.Data = matches[i][5]
} else if matches[i][6] == "&" {
param.ParamType = MetaReference // Reference to template
param.Data = matches[i][7]
} else if matches[i][8] == "@" {
param.ParamType = MetaRange // Loop on data
param.Data = matches[i][9]
} else if matches[i][10] == "?" {
param.ParamType = MetaCondition // Conditional on data
param.Data = matches[i][11]
} else if matches[i][12] == "!" {
param.ParamType = MetaDump // Debug
param.Data = matches[i][13]
} else if matches[i][14] == "{" {
param.ParamType = MetaVariable // Simple element
param.Data = matches[i][15]
} else if matches[i][18] == "[" {
param.ParamType = MetaTemplateStart // Template start
param.Data = matches[i][19]
} else if matches[i][16] == "]" {
param.ParamType = MetaTemplateEnd // Template end
} else {
param.ParamType = MetaUnused // unknown, will be removed
}
compiled = append(compiled, *param)
pointer = x[1]
}
// end of Data
if pointer != len(data) {
compiled = append(compiled, *(&XTemplateParam{ParamType: MetaString, Data: data[pointer:]}))
}
// second pass: all the sub templates into the Subtemplates
startpointers := []int{}
subtemplates := []*XTemplate{}
actualtemplate := t
for i, x := range compiled {
if x.ParamType == MetaTemplateStart {
startpointers = append(startpointers, i)
subtemplates = append(subtemplates, actualtemplate)
actualtemplate = &XTemplate{Name: x.Data, Root: nil}
} else if x.ParamType == MetaTemplateEnd {
// we found the end of the nested box, lets create a nested param array from stacked startpointer up to i
last := len(startpointers) - 1
if last < 0 {
return errors.New("Error: template mismatch Start/End")
}
startpointer := startpointers[last]
startpointers = startpointers[:last]
var subset XTemplateData
for ptr := startpointer + 1; ptr < i; ptr++ { // we ignore the BOX]] end param (we dont need it in the hierarchic structure)
if compiled[ptr].ParamType != MetaUnused { // we just ignore params marked to be deleted
subset = append(subset, compiled[ptr])
compiled[ptr].ParamType = MetaUnused // marked to be deleted, traslated to a substructure
}
}
actualtemplate.Root = &subset
uppertemplate := subtemplates[last]
subtemplates = subtemplates[:last]
// If there are |, we separate the templates and add every one to the list with same pointer
pospipe := strings.Index(actualtemplate.Name, "|")
if pospipe >= 0 {
vals := strings.Split(actualtemplate.Name, "|")
for _, v := range vals {
if len(v) > 0 {
uppertemplate.AddTemplate(v, actualtemplate)
}
}
} else {
uppertemplate.AddTemplate(actualtemplate.Name, actualtemplate)
}
// pop actualtemplate
actualtemplate = uppertemplate
compiled[startpointer].ParamType = MetaUnused // marked to be deleted, no need of start template
compiled[i].ParamType = MetaUnused // marked to be deleted, no need of end template
}
}
if len(startpointers) > 0 {
return errors.New("Error: template mismatch Start/End")
}
// last pass: delete params marked to be deleted and concatenate strings
currentpointer := 0
for i, x := range compiled {
if x.ParamType != MetaUnused {
if currentpointer != i {
compiled[currentpointer] = x
}
currentpointer++
}
}
compiled = compiled[:currentpointer]
t.Root = &compiled
return nil
}
// AddTemplate will add a sub template to this template
func (t *XTemplate) AddTemplate(name string, tmpl *XTemplate) {
if t.SubTemplates == nil {
t.SubTemplates = make(map[string]*XTemplate)
}
t.SubTemplates[name] = tmpl
}
// GetTemplate gets a sub template existing into this template
func (t *XTemplate) GetTemplate(name string) *XTemplate {
if t.SubTemplates == nil {
return nil
}
return t.SubTemplates[name]
}
// Execute will inject the Data into the template and creates the final string
func (t *XTemplate) Execute(data XDatasetDef) string {
// Does data has a language ?
if data != nil {
var language *XLanguage
lang, _ := data.Get("#")
if lang != nil {
language, _ = lang.(*XLanguage) // language is nil if it-s not a *XLanguage
}
stack := &XDatasetCollection{}
stack.Push(data)
return t.injector(stack, language)
}
return t.injector(nil, nil)
}
// injector will injects the data into this template
func (t *XTemplate) injector(datacol XDatasetCollectionDef, language *XLanguage) string {
var injected []string
if t.Root == nil {
return "Error, no template.Root compiled"
}
for _, v := range *t.Root {
switch v.ParamType {
case MetaString: // included string from original code
injected = append(injected, v.Data)
case MetaComment:
// nothing to do: comment ignored
case MetaLanguage:
if language != nil {
injected = append(injected, language.Get(v.Data))
}
case MetaReference: // Reference &&
xid := strings.Split(v.Data, ":")
if len(xid) == 3 {
field := xid[1]
prefix := xid[2]
value, _ := datacol.GetDataString(field)
subt := t.GetTemplate(prefix + value)
if subt != nil {
substr := subt.injector(datacol, language)
injected = append(injected, substr)
} else {
subt := t.GetTemplate(prefix)
if subt != nil {
substr := subt.injector(datacol, language)
injected = append(injected, substr)
}
}
} else {
template := ""
if len(xid) >= 1 {
template = xid[0]
}
subt := t.GetTemplate(template)
if subt != nil {
withds := false
if len(xid) == 2 {
dcl, _ := datacol.GetData(xid[1])
ds, ok := dcl.(XDatasetDef)
if ok {
withds = true
datacol.Push(ds)
}
}
substr := subt.injector(datacol, language)
if withds {
datacol.Pop()
}
injected = append(injected, substr)
}
}
case MetaVariable: // {{id>id>id...}}
if datacol != nil {
d, _ := datacol.GetDataString(v.Data)
injected = append(injected, d)
}
case MetaRange: // Range (loop over subset) @@id:id@@
xdata := strings.Split(v.Data, ":")
subdataid := xdata[0]
subtemplateid := xdata[0]
if len(xdata) > 1 {
subtemplateid = xdata[1]
}
subt := t.GetTemplate(subtemplateid)
if subt != nil {
if datacol != nil {
cl, _ := datacol.GetCollection(subdataid)
if cl != nil {
for i := 0; i < cl.Count(); i++ {
var tmp *XTemplate
tmp = t.GetTemplate(subtemplateid + ".key." + strconv.Itoa(i))
// if tmp == nil {
// tmp = t.GetTemplate(subtemplateid + ".field." + field + "." + value)
// }
if tmp == nil && i == 0 {
tmp = t.GetTemplate(subtemplateid + ".first")
}
if tmp == nil && i == cl.Count()-1 {
tmp = t.GetTemplate(subtemplateid + ".last")
}
if tmp == nil && i%2 == 0 {
tmp = t.GetTemplate(subtemplateid + ".even")
}
if tmp == nil {
tmp = subt
}
dcl, _ := cl.Get(i)
datacol.Push(dcl)
substr := tmp.injector(datacol, language)
injected = append(injected, substr)
// unstack extra data
datacol.Pop()
}
} else {
var tmp *XTemplate
tmp = t.GetTemplate(subtemplateid + ".none")
if tmp == nil {
tmp = subt
}
substr := tmp.injector(datacol, language)
injected = append(injected, substr)
}
}
}
case MetaCondition: // ??id??
xdata := strings.Split(v.Data, ":")
subdataid := xdata[0]
subtemplateid := xdata[0]
if len(xdata) > 1 {
subtemplateid = xdata[1]
}
subt := t.GetTemplate(subtemplateid)
var value interface{}
if datacol != nil {
value, _ = datacol.GetData(subdataid)
}
if subt != nil && value != nil {
withds := false
svalue := ""
ds, ok := value.(XDatasetDef)
if ok {
withds = true
datacol.Push(ds)
} else {
svalue = fmt.Sprint(value)
}
if svalue != "" {
// subtemplate with .value?
tmp := t.GetTemplate(subtemplateid + "." + svalue)
if tmp != nil {
subt = tmp
}
substr := subt.injector(datacol, language)
injected = append(injected, substr)
}
if withds {
datacol.Pop()
}
}
case MetaDump:
if datacol != nil {
if v.Data == "dump" || v.Data == "list" {
dsubstr, _ := datacol.Get(0)
if dsubstr != nil {
substr := dsubstr.GoString()
injected = append(injected, substr)
}
}
}
default:
injected = append(injected, "THE METALANGUAGE FROM OUTERSPACE IS NOT SUPPORTED: "+fmt.Sprint(v.ParamType))
}
}
// return the page string
return strings.Join(injected, "")
}
// String will transform the XDataset into a readable string for humans
func (t *XTemplate) String() string {
sdata := []string{}
for _, val := range *t.Root {
sdata = append(sdata, fmt.Sprintf("%v", val))
}
sort.Strings(sdata) // Lets be sure the print is always the same presentation
return "xcore.XLanguage{" + strings.Join(sdata, " ") + "}"
}
// GoString will transform the XDataset into a readable string for humans
func (t *XTemplate) GoString() string {
return t.String()
}