-
-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathmormot.core.mustache.pas
2478 lines (2320 loc) · 81.8 KB
/
mormot.core.mustache.pas
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// Framework Core {{mustache}} Templates Renderer
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.core.mustache;
{
*****************************************************************************
Logic-Less Mustache Templates Rendering
- Mustache Execution Data Context Types
- TSynMustache Template Processing
*****************************************************************************
}
interface
{$I ..\mormot.defines.inc}
uses
classes,
sysutils,
variants,
mormot.core.base,
mormot.core.os,
mormot.core.unicode,
mormot.core.text,
mormot.core.search, // for TSynMustache.Match helper
mormot.core.buffers,
mormot.core.datetime,
mormot.core.rtti,
mormot.core.json,
mormot.core.data,
mormot.core.variants;
{ ************ Mustache Execution Data Context Types }
type
/// exception raised during process of a {{mustache}} template
ESynMustache = class(ESynException);
/// identify the {{mustache}} tag kind
// - sorted by occurence, to optimize RenderContext() process
// - mtText for all text that appears outside a symbol
// - mtVariable if the tag is a variable - e.g. {{myValue}} - or an Expression
// Helper - e.g. {{helperName valueName}}
// - mtVariableUnescape, mtVariableUnescapeAmp to unescape the variable HTML - e.g.
// {{{myRawValue}}} or {{& name}}
// - mtSection and mtInvertedSection for sections beginning - e.g.
// {{#person}} or {{^person}}
// - mtSectionEnd for sections ending - e.g. {{/person}}
// - mtComment for comments - e.g. {{! ignore me}}
// - mtPartial for partials - e.g. {{> next_more}}
// - mtSetPartial for setting an internal partial - e.g.
// {{<foo}}This is the foo partial {{myValue}} template{{/foo}}
// - mtSetDelimiter for setting custom delimeter symbols - e.g. {{=<% %>=}} -
// Warning: current implementation only supports two character delimiters
// - mtTranslate for content i18n via a callback - e.g. {{"English text}}
TSynMustacheTagKind = (
mtText,
mtVariable,
mtVariableUnescape,
mtVariableUnescapeAmp,
mtSection,
mtInvertedSection,
mtSectionEnd,
mtComment,
mtPartial,
mtSetPartial,
mtSetDelimiter,
mtTranslate);
/// store a {{mustache}} tag parsed definition
TSynMustacheTag = record
/// points to the mtText buffer start
// - main template's text is not allocated as a separate string during
// parsing, but will rather be copied directly from the template memory
TextStart: PUtf8Char;
/// stores the mtText buffer length
TextLen: integer;
/// the index in Tags[] of the other end of this section (16-bit)
// - either the index of mtSectionEnd for mtSection/mtInvertedSection
// - or the index of mtSection/mtInvertedSection for mtSectionEnd
SectionOppositeIndex: SmallInt;
/// the kind of the tag
Kind: TSynMustacheTagKind;
/// if the Value has an included ' ' within, i.e. could be an helper
// - equals PosExChar(' ', Value)
ValueSpace: byte;
/// the tag content, excluding trailing {{ }} and corresponding symbol
// - is not set for mtText nor mtSetDelimiter
Value: RawUtf8;
end;
/// pointer reference to a {{mustache}} tag parsed definition
PSynMustacheTag = ^TSynMustacheTag;
/// store all {{mustache}} tags of a given template
TSynMustacheTagDynArray = array of TSynMustacheTag;
/// states the section content according to a given value
// - msNothing for false values or empty lists
// - msSingle for non-false values but not a list
// - msSinglePseudo is for *-first *-last *-odd and helper values
// - msList for non-empty lists
TSynMustacheSectionType = (
msNothing,
msSingle,
msSinglePseudo,
msList);
TSynMustache = class;
/// callback signature used to process an Expression Helper variable
// - i.e. {{helperName value}} tags
// - returned value will be used to process as replacement of a single {{tag}}
TSynMustacheHelperEvent =
procedure(const Value: variant; out Result: variant) of object;
/// used to store a registered Expression Helper implementation
TSynMustacheHelper = record
/// the Expression Helper name
Name: RawUtf8;
/// the corresponding callback to process the tag
Event: TSynMustacheHelperEvent;
end;
/// used to store all registered Expression Helpers
// - i.e. {{helperName value}} tags
// - use TSynMustache.HelperAdd/HelperDelete class methods to manage the list
// or retrieve standard helpers via TSynMustache.HelpersGetStandardList
TSynMustacheHelpers = array of TSynMustacheHelper;
TSynMustachePartials = class;
/// handle {{mustache}} template rendering context, i.e. all values
// - this abstract class should not be used directly, but rather any
// other overridden class
TSynMustacheContext = class
protected
fReuse: TLightLock; // topmost to ensure aarch64 alignment
fContextCount: integer;
fEscapeInvert: boolean;
fOwnWriter: boolean;
fGetVarDataFromContextNeedsFree: boolean;
fPathDelim: AnsiChar;
fWriter: TJsonWriter;
fHelpers: TSynMustacheHelpers;
fPartials: TSynMustachePartials;
fTempProcessHelper: TVariantDynArray;
fOnStringTranslate: TOnStringTranslate;
fOwner: TSynMustache;
// some variant support is needed for the helpers
function ProcessHelper(const ValueName: RawUtf8; space, helper: PtrInt;
var Value: TVarData; OwnValue: PPVarData): TSynMustacheSectionType; virtual;
function GetHelperFromContext(ValueSpace: integer; const ValueName: RawUtf8;
var Value: TVarData; OwnValue: PPVarData): TSynMustacheSectionType;
procedure TranslateBlock(Text: PUtf8Char; TextLen: integer); virtual;
function GetVariantFromContext(const ValueName: RawUtf8): variant;
procedure PopContext;
// inherited class should override those methods used by RenderContext()
function GotoNextListItem: boolean;
virtual; abstract;
function GetVarDataFromContext(ValueSpace: integer; const ValueName: RawUtf8;
var Value: TVarData): TSynMustacheSectionType; virtual; abstract;
procedure AppendValue(ValueSpace: integer; const ValueName: RawUtf8;
UnEscape: boolean); virtual; abstract;
function AppendSection(ValueSpace: integer;
const ValueName: RawUtf8): TSynMustacheSectionType; virtual; abstract;
public
/// initialize the rendering context for the given text writer
constructor Create(Owner: TSynMustache; WR: TJsonWriter; OwnWR: boolean);
/// release this rendering context instance
destructor Destroy; override;
/// allow to reuse this Mustache template rendering context
procedure CancelAll;
/// the registered Expression Helpers, to handle {{helperName value}} tags
// - use TSynMustache.HelperAdd/HelperDelete class methods to manage the list
// or retrieve standard helpers via TSynMustache.HelpersGetStandardList
property Helpers: TSynMustacheHelpers
read fHelpers write fHelpers;
/// access to the custom Partials associated with this execution context
property Partials: TSynMustachePartials
read fPartials write fPartials;
/// access to the {{"English text}} translation callback
property OnStringTranslate: TOnStringTranslate
read fOnStringTranslate write fOnStringTranslate;
/// read-only access to the associated text writer instance
property Writer: TJsonWriter
read fWriter;
/// invert the HTML characters escaping process
// - by default, {{value}} will escape value chars, and {{{value}} won't
// - set this property to true to force {{value}} NOT to escape HTML chars
// and {{{value}} escaping chars (may be useful e.g. for code generation)
property EscapeInvert: boolean
read fEscapeInvert write fEscapeInvert;
/// the path delimited for getting a value
// - equals '.' by default
property PathDelim: AnsiChar
read fPathDelim write fPathDelim;
end;
/// handle {{mustache}} template rendering context from a custom variant
// - the context is given via a custom variant type implementing
// TSynInvokeableVariantType.Lookup, e.g. TDocVariant or TSMVariant
TSynMustacheContextVariant = class(TSynMustacheContext)
protected
fContext: array of record
Document: TVarData;
DocumentType: TSynInvokeableVariantType;
ListCount: integer;
ListCurrent: integer;
ListCurrentDocument: TVarData;
ListCurrentDocumentType: TSynInvokeableVariantType;
end;
procedure PushContext(const aDoc: TVarData);
function GotoNextListItem: boolean; override;
function GetVarDataFromContext(ValueSpace: integer; const ValueName: RawUtf8;
var Value: TVarData): TSynMustacheSectionType; override;
procedure AppendValue(ValueSpace: integer; const ValueName: RawUtf8;
UnEscape: boolean); override;
function AppendSection(ValueSpace: integer;
const ValueName: RawUtf8): TSynMustacheSectionType; override;
public
/// initialize the context from a custom variant document
// - note that the aDocument instance shall be available during all
// lifetime of this TSynMustacheContextVariant instance
// - you should not use this constructor directly, but the
// corresponding TSynMustache.Render*() methods
constructor Create(Owner: TSynMustache; WR: TJsonWriter;
SectionMaxCount: integer; const aDocument: variant; OwnWriter: boolean);
/// render this reusable rendering context
// - wrap PushContext + Owner.RenderContext + Writer.SetText + CancelAll
function Render(const aDoc: variant): RawUtf8;
end;
TSynMustacheContextData = class;
/// TSynMustacheContextData.OnGetGlobalData callback signature
// - Data and Rtti are filled with the {{.}} current context at call
// - implementation should lookup ValueName and set Data/Rtti with result=true
// - warning: the returned Data pointer should remain active until the
// Mustache rendering task is completed
TOnGetGlobalData = function(Sender: TSynMustacheContextData;
const ValueName: RawUtf8; var Data: pointer; var Rtti: TRttiCustom): boolean;
/// handle {{mustache}} template rendering context from RTTI and variables
// - the context is given via our RTTI information
// - performance is somewhat higher than TSynMustacheContextVariant because
// less computation is needed for filling transient TDocVariant instances
TSynMustacheContextData = class(TSynMustacheContext)
protected
fContext: array of record
Data: pointer;
Info: TRttiCustom;
ListCount: integer;
ListCurrent: integer;
Temp: TSynVarData;
end;
fOnGetGlobalData: TOnGetGlobalData;
procedure PushContext(Value: pointer; Rtti: TRttiCustom);
function GotoNextListItem: boolean; override;
function GetDataFromContext(const ValueName: RawUtf8;
out rc: TRttiCustom; out d: pointer): boolean;
function GetVarDataFromContext(ValueSpace: integer; const ValueName: RawUtf8;
var Value: TVarData): TSynMustacheSectionType; override;
procedure AppendValue(ValueSpace: integer; const ValueName: RawUtf8;
UnEscape: boolean); override;
function AppendSection(ValueSpace: integer;
const ValueName: RawUtf8): TSynMustacheSectionType; override;
public
/// initialize the context from a document stored in a local variable
// - note that the variable instance shall be available during all
// lifetime of this TSynMustacheContextData instance
// - you should not use this constructor directly, but the
// corresponding TSynMustache.RenderData() methods
constructor Create(Owner: TSynMustache; WR: TJsonWriter;
SectionMaxCount: integer; Value: pointer; ValueRtti: TRttiCustom;
OwnWriter: boolean);
/// render this reusable rendering context
// - wrap PushContext + Owner.RenderContext + Writer.SetText + CancelAll
function RenderArray(const arr: TDynArray): RawUtf8;
/// render this reusable rendering context
// - wrap PushContext + Owner.RenderContext + Writer.SetText + CancelAll
function RenderRtti(Value: pointer; Rtti: TRttiCustom): RawUtf8;
/// callback to get data at runtime from a global name
// - when the Value variable provided to TSynMustache.RenderData is not enough
property OnGetGlobalData: TOnGetGlobalData
read fOnGetGlobalData write fOnGetGlobalData;
end;
/// maintain a list of {{mustache}} partials
// - this list of partials template could be supplied to TSynMustache.Render()
// method, to render {{>partials}} as expected
// - using a dedicated class allows to share the partials between execution
// context, without recurring to non SOLID global variables
// - you may also define "internal" partials, e.g. {{<foo}}This is foo{{/foo}}
TSynMustachePartials = class
protected
fList: TRawUtf8List;
fOwned: boolean;
function GetPartial(const PartialName: RawUtf8): TSynMustache;
public
/// initialize the template partials storage
// - after creation, the partials should be registered via the Add() method
// - you shall manage this instance life time with a try..finally Free block
constructor Create; overload;
/// initialize a template partials storage with the supplied templates
// - partials list is expected to be supplied in Name / Template pairs
// - this instance can be supplied as parameter to the TSynMustache.Render()
// method, which will free the instances as soon as it finishes
constructor CreateOwned(
const NameTemplatePairs: array of RawUtf8); overload;
/// initialize a template partials storage with the supplied templates
// - partials list is expected to be supplied as a dvObject TDocVariant,
// each member being the name/template string pairs
// - if the supplied variant is not a matching TDocVariant, will return nil
// - this instance can be supplied as parameter to the TSynMustache.Render()
// method, which will free the instances as soon as it finishes
class function CreateOwned(
const Partials: variant): TSynMustachePartials; overload;
/// register a {{>partialName}} template
// - returns the parsed template
function Add(const aName,aTemplate: RawUtf8): TSynMustache; overload;
/// register a {{>partialName}} template
// - returns the parsed template
function Add(const aName: RawUtf8;
aTemplateStart, aTemplateEnd: PUtf8Char): TSynMustache; overload;
/// search some text withing the {{mustache}} partial
function FoundInTemplate(const text: RawUtf8): PtrInt;
/// delete the partials
destructor Destroy; override;
/// low-level access to the internal partials list
property List: TRawUtf8List
read fList;
end;
{ ************ TSynMustache Template Processing }
/// handles one {{mustache}} pre-rendered template
// - once parsed, a template will be stored in this class instance, to be
// rendered lated via the Render() method
// - you can use the Parse() class function to maintain a shared cache of
// parsed templates
// - implements all official mustache specifications, and some extensions
// - handles {{.}} pseudo-variable for the current context object (very
// handy when looping through a simple list, for instance)
// - handles {{-index}} pseudo-variable for the current context array index
// (1-based value) so that e.g.
// "My favorite things:\n{{#things}}{{-index}}. {{.}}\n{{/things}}"
// over {things:["Peanut butter", "Pen spinning", "Handstands"]} renders as
// "My favorite things:\n1. Peanut butter\n2. Pen spinning\n3. Handstands\n"
// - you could use {{-index0}} for 0-based index value
// - handles -first -last and -odd pseudo-section keys, e.g.
// "{{#things}}{{^-first}}, {{/-first}}{{.}}{{/things}}"
// over {things:["one", "two", "three"]} renders as 'one, two, three'
// - allows inlined partial templates , to be defined e.g. as
// {{<foo}}This is the foo partial {{myValue}} template{{/foo}}
// - features {{"English text}} translation, via a custom callback
// - this implementation is thread-safe and re-entrant (i.e. the same
// TSynMustache instance can be used by several threads at once)
TSynMustache = class
protected
fTemplate: RawUtf8;
fTags: TSynMustacheTagDynArray;
fInternalPartials: TSynMustachePartials;
fSectionMaxCount: integer;
fCachedContextVariant: TSynMustacheContextVariant;
fCachedContextData: TSynMustacheContextData;
// standard helpers implementation
class procedure DateTimeToText(const Value: variant; out Result: variant);
class procedure DateToText(const Value: variant; out Result: variant);
class procedure DateFmt(const Value: variant; out Result: variant);
class procedure TimeLogToText(const Value: variant; out Result: variant);
class procedure BlobToBase64(const Value: variant; out Result: variant);
class procedure ToJson(const Value: variant; out Result: variant);
class procedure JsonQuote(const Value: variant; out Result: variant);
class procedure JsonQuoteUri(const Value: variant; out Result: variant);
class procedure WikiToHtml(const Value: variant; out Result: variant);
class procedure MarkdownToHtml(const Value: variant; out Result: variant);
class procedure SimpleToHtml(const Value: variant; out Result: variant);
class procedure Match(const Value: variant; out Result: variant);
class procedure MatchI(const Value: variant; out Result: variant);
class procedure Lower(const Value: variant; out Result: variant);
class procedure Upper(const Value: variant; out Result: variant);
class procedure CamelCase(const Value: variant; out Result: variant);
class procedure SnakeCase(const Value: variant; out Result: variant);
class procedure EnumTrim(const Value: variant; out Result: variant);
class procedure EnumTrimRight(const Value: variant; out Result: variant);
class procedure PowerOfTwo(const Value: variant; out Result: variant);
class procedure Equals_(const Value: variant; out Result: variant);
class procedure If_(const Value: variant; out Result: variant);
class procedure NewGuid(const Value: variant; out Result: variant);
class procedure ExtractFileName(const Value: variant; out Result: variant);
class procedure HumanBytes(const Value: variant; out Result: variant);
class procedure Sub(const Value: variant; out Result: variant);
class procedure Values(const Value: variant; out Result: variant);
class procedure Keys(const Value: variant; out Result: variant);
public
/// parse a {{mustache}} template, and returns the corresponding
// TSynMustache instance
// - an internal cache is maintained by this class function
// - don't free the returned instance: it is owned by the cache
// - this implementation is thread-safe and re-entrant: i.e. the same
// TSynMustache returned instance can be used by several threads at once
// - will raise an ESynMustache exception on error
class function Parse(const aTemplate: RawUtf8): TSynMustache;
/// remove the specified {{mustache}} template from the internal cache
// - returns TRUE on success, or FALSE if the template was not cached
// by a previous call to Parse() class function
class function UnParse(const aTemplate: RawUtf8): boolean;
/// parse and render a {{mustache}} template over the supplied JSON
// - an internal templates cache is maintained by this class function
// - returns TRUE and set aContent the rendered content on success
// - returns FALSE if the template is not correct
class function TryRenderJson(const aTemplate, aJson: RawUtf8;
out aContent: RawUtf8): boolean;
public
/// initialize and parse a pre-rendered {{mustache}} template
// - you should better use the Parse() class function instead, which
// features an internal thread-safe cache
constructor Create(const aTemplate: RawUtf8); overload;
/// initialize and parse a pre-rendered {{mustache}} template
// - you should better use the Parse() class function instead, which
// features an internal thread-safe cache
constructor Create(
aTemplate: PUtf8Char; aTemplateLen: integer); overload; virtual;
/// finalize internal memory
destructor Destroy; override;
/// internal factory calling TSynMustacheContextVariant.Create()
// - to call e.g. result.Render() several times
function NewMustacheContextVariant(
aBufSize: integer = 16384): TSynMustacheContextVariant;
/// internal factory calling TSynMustacheContextData.Create()
// - to call e.g. result.RenderArray() or result.RenderRtti() several times
function NewMustacheContextData(
aBufSize: integer = 16384): TSynMustacheContextData;
/// search some text within the {{mustache}} template text
function FoundInTemplate(const text: RawUtf8): boolean;
/// register one Expression Helper callback for a given list of helpers
// - i.e. to let aEvent process {{aName value}} tags
// - the supplied name will be checked against the current list, and replace
// any existing entry
class procedure HelperAdd(var Helpers: TSynMustacheHelpers;
const aName: RawUtf8; aEvent: TSynMustacheHelperEvent); overload;
/// register several Expression Helper callbacks for a given list of helpers
// - the supplied names will be checked against the current list, and replace
// any existing entry
class procedure HelperAdd(var Helpers: TSynMustacheHelpers;
const aNames: array of RawUtf8;
const aEvents: array of TSynMustacheHelperEvent); overload;
/// unregister one Expression Helper callback for a given list of helpers
class procedure HelperDelete(var Helpers: TSynMustacheHelpers;
const aName: RawUtf8);
/// search for one Expression Helper event by name
class function HelperFind(const Helpers: TSynMustacheHelpers;
aName: PUtf8Char; aNameLen: TStrLen): PtrInt;
/// returns a list of most used static Expression Helpers
// - registered helpers are DateTimeToText, DateToText, DateFmt, TimeLogToText,
// BlobToBase64, JsonQuote, JsonQuoteUri, ToJson, EnumTrim, EnumTrimRight,
// Lower / Upper (Unicode ready), CamelCase / SnakeCase, PowerOfTwo, Equals
// (expecting two parameters), NewGuid, ExtractFileName, HumanBytes (calling
// KB function), Sub (as {{Sub AString,12,3}}), MarkdownToHtml, SimpleToHtml
// (Markdown with no HTML pass-through), WikiToHtml (calling
// TJsonWriter.AddHtmlEscapeWiki), Match / MatchI (as {{Match AString,startwith*}}),
// and Values / Keys (over a data object)
// - an additional #if helper is also registered, which would allow runtime
// view logic, via = < > <= >= <> operators over two values:
// $ {{#if .,"=",123}} {{#if Total,">",1000}} {{#if info,"<>",""}}
// which may be shortened as such:
// $ {{#if .=123}} {{#if Total>1000}} {{#if info<>""}}
class function HelpersGetStandardList: TSynMustacheHelpers; overload;
/// returns a list of most used static Expression Helpers, adding some
// custom callbacks
// - is just a wrapper around HelpersGetStandardList and HelperAdd()
class function HelpersGetStandardList(const aNames: array of RawUtf8;
const aEvents: array of TSynMustacheHelperEvent): TSynMustacheHelpers; overload;
/// renders the {{mustache}} template into a destination text buffer
// - the context is given via our abstract TSynMustacheContext wrapper
// - the rendering extended in fTags[] is supplied as parameters
// - you can specify a list of partials via TSynMustachePartials.CreateOwned
procedure RenderContext(Context: TSynMustacheContext;
TagStart, TagEnd: PtrInt);
/// renders the {{mustache}} template from a variant defined context
// - the context is given via a custom variant type implementing
// TSynInvokeableVariantType.Lookup, e.g. TDocVariant or TSMVariant
// - you can specify a list of partials via TSynMustachePartials.CreateOwned,
// a list of Expression Helpers, or a custom {{"English text}} callback
// - can be used e.g. via a TDocVariant:
// !var
// ! mustache := TSynMustache;
// ! doc: variant;
// ! html: RawUtf8;
// !begin
// ! mustache := TSynMustache.Parse(
// ! 'Hello {{name}}'#13#10'You have just won {{value}} dollars!');
// ! TDocVariant.New(doc);
// ! doc.name := 'Chris';
// ! doc.value := 10000;
// ! html := mustache.Render(doc);
// ! // here html='Hello Chris'#13#10'You have just won 10000 dollars!'
// - you can also retrieve the context from an ORM query:
// ! dummy := TSynMustache.Parse(
// ! '{{#items}}'#13#10'{{Int}}={{Test}}'#13#10'{{/items}}').Render(
// ! aClient.RetrieveDocVariantArray(TOrmTest, 'items', 'Int,Test'));
// - set EscapeInvert = true to force {{value}} NOT to escape HTML chars
// and {{{value}} escaping chars (may be useful e.g. for code generation)
function Render(const Context: variant;
Partials: TSynMustachePartials = nil;
const Helpers: TSynMustacheHelpers = nil;
const OnTranslate: TOnStringTranslate = nil;
EscapeInvert: boolean = false): RawUtf8;
/// renders the {{mustache}} template from JSON defined context
// - the context is given via a JSON object, defined from UTF-8 buffer
// - you can specify a list of partials via TSynMustachePartials.CreateOwned,
// a list of Expression Helpers, or a custom {{"English text}} callback
// - is just a wrapper around Render(_JsonFast())
// - you can write e.g. with the extended JSON syntax:
// ! html := mustache.RenderJson('{things:["one", "two", "three"]}');
// - set EscapeInvert = true to force {{value}} NOT to escape HTML chars
// and {{{value}} escaping chars (may be useful e.g. for code generation)
function RenderJson(const Json: RawUtf8;
Partials: TSynMustachePartials = nil;
const Helpers: TSynMustacheHelpers = nil;
const OnTranslate: TOnStringTranslate = nil;
EscapeInvert: boolean = false): RawUtf8; overload;
/// renders the {{mustache}} template from JSON defined context
// - the context is given via a JSON object, defined with parameters
// - you can specify a list of partials via TSynMustachePartials.CreateOwned,
// a list of Expression Helpers, or a custom {{"English text}} callback
// - is just a wrapper around Render(_JsonFastFmt())
// - you can write e.g. with the extended JSON syntax:
// ! html := mustache.RenderJson('{name:?,value:?}',[],['Chris',10000]);
// - set EscapeInvert = true to force {{value}} NOT to escape HTML chars
// and {{{value}} escaping chars (may be useful e.g. for code generation)
function RenderJson(const Json: RawUtf8;
const Args, Params: array of const;
Partials: TSynMustachePartials = nil;
const Helpers: TSynMustacheHelpers = nil;
const OnTranslate: TOnStringTranslate = nil;
EscapeInvert: boolean = false): RawUtf8; overload;
/// renders the {{mustache}} template from a variable defined context
// - the context is given via a local variable and RTTI, which may be
// a record, a class, a variant, or a dynamic array instance
// - you can specify a list of partials via TSynMustachePartials.CreateOwned,
// a list of Expression Helpers, or a custom {{"English text}} callback
// - set EscapeInvert = true to force {{value}} NOT to escape HTML chars
// and {{{value}} escaping chars (may be useful e.g. for code generation)
// - just redirects to the RenderDataRtti() method
function RenderData(const Value; ValueTypeInfo: PRttiInfo;
const OnGetData: TOnGetGlobalData = nil;
Partials: TSynMustachePartials = nil;
const Helpers: TSynMustacheHelpers = nil;
const OnTranslate: TOnStringTranslate = nil;
EscapeInvert: boolean = false): RawUtf8;
/// renders the {{mustache}} template from a dynamic array variable
// - the supplied array is available within a {{.}} main section
// - you can specify a list of partials via TSynMustachePartials.CreateOwned,
// a list of Expression Helpers, or a custom {{"English text}} callback
// - set EscapeInvert = true to force {{value}} NOT to escape HTML chars
// and {{{value}} escaping chars (may be useful e.g. for code generation)
// - just redirects to the RenderDataRtti() method
function RenderDataArray(const Value: TDynArray;
const OnGetData: TOnGetGlobalData = nil;
Partials: TSynMustachePartials = nil;
const Helpers: TSynMustacheHelpers = nil;
const OnTranslate: TOnStringTranslate = nil;
EscapeInvert: boolean = false): RawUtf8;
/// renders the {{mustache}} template from a variable and its RTTI
// - the context is given via a local variable and RTTI, which may be
// a record, a class, a variant, or a dynamic array instance
// - you can specify a list of partials via TSynMustachePartials.CreateOwned,
// a list of Expression Helpers, or a custom {{"English text}} callback
// - set EscapeInvert = true to force {{value}} NOT to escape HTML chars
// and {{{value}} escaping chars (may be useful e.g. for code generation)
function RenderDataRtti(Value: pointer; ValueRtti: TRttiCustom;
const OnGetData: TOnGetGlobalData = nil;
Partials: TSynMustachePartials = nil;
const Helpers: TSynMustacheHelpers = nil;
const OnTranslate: TOnStringTranslate = nil;
EscapeInvert: boolean = false): RawUtf8;
/// read-only access to the raw UTF-8 {{mustache}} template content
property Template: RawUtf8
read fTemplate;
/// read-only access to the internal representation of the template
property Tags: TSynMustacheTagDynArray
read fTags;
/// the maximum possible number of nested contexts
// - i.e. the depth of nested {{#....}} {{/....}} sections
property SectionMaxCount: integer
read fSectionMaxCount;
end;
const
/// Mustache-friendly JSON Serialization Options
// - as used e.g. from mormot.rest.mvc Data Context from Cookies
TEXTWRITEROPTIONS_MUSTACHE =
[twoForceJsonExtended,
twoEnumSetsAsBooleanInRecord,
twoTrimLeftEnumSets];
/// this constant can be used to define as JSON a tag value
NULL_OR_TRUE: array[boolean] of RawUtf8 = (
'null', 'true');
/// this constant can be used to define as JSON a tag value as separator
NULL_OR_COMMA: array[boolean] of RawUtf8 = (
'null', '","');
implementation
{ ************ Mustache Execution Data Context Types }
{ TSynMustacheContext }
constructor TSynMustacheContext.Create(Owner: TSynMustache;
WR: TJsonWriter; OwnWR: boolean);
begin
fOwner := Owner;
fOwnWriter := OwnWR;
fWriter := WR;
fPathDelim := '.';
end;
destructor TSynMustacheContext.Destroy;
begin
inherited Destroy;
if fOwnWriter then
fWriter.Free;
end;
procedure TSynMustacheContext.PopContext;
begin
if fContextCount > 1 then
dec(fContextCount);
end;
procedure TSynMustacheContext.TranslateBlock(Text: PUtf8Char; TextLen: integer);
var
s: string;
begin
if Assigned(OnStringTranslate) then
begin
Utf8DecodeToString(Text, TextLen, s);
OnStringTranslate(s);
fWriter.AddNoJsonEscapeString(s);
end
else
fWriter.AddNoJsonEscape(Text, TextLen);
end;
function TSynMustacheContext.GetVariantFromContext(
const ValueName: RawUtf8): variant;
var
tmp: TVarData;
begin
if (ValueName = '') or
(ValueName[1] in ['-', '0'..'9', '"', '{', '[']) or
(ValueName = 'true') or
(ValueName = 'false') or
(ValueName = 'null') then
VariantLoadJson(result, ValueName, @JSON_[mFast])
else if fGetVarDataFromContextNeedsFree then
begin
if TVarData(result).VType <> varEmpty then
VarClearProc(TVarData(result));
GetVarDataFromContext(-1, ValueName, TVarData(result)); // set directly
end
else
begin
GetVarDataFromContext(-1, ValueName, tmp); // get TVarData content
SetVariantByValue(variant(tmp), result, false); // assign/copy value
end;
end;
function TSynMustacheContext.ProcessHelper(const ValueName: RawUtf8;
space, helper: PtrInt; var Value: TVarData;
OwnValue: PPVarData): TSynMustacheSectionType;
var
valnam: RawUtf8;
p: PUtf8Char;
val: TVarData;
valArr: TDocVariantData absolute val;
valFree, valFound: boolean;
names: TRawUtf8DynArray;
j, k, n: PtrInt;
begin
valnam := Copy(ValueName, space + 1, maxInt);
TSynVarData(val).VType := varEmpty;
valFree := fGetVarDataFromContextNeedsFree;
if valnam <> '' then
begin
if valnam = '.' then
GetVarDataFromContext(-1, valnam, val)
else if ((valnam <> '') and
(valnam[1] in ['1'..'9', '"', '{', '['])) or
(valnam = 'true') or
(valnam = 'false') or
(valnam = 'null') then
begin
// {{helper 123}} or {{helper "constant"}} or {{helper [1,2,3]}}
JsonToVariantInPlace(variant(val), pointer(valnam), JSON_FAST_FLOAT);
valFree := true;
end
else
begin
valFound := false;
for j := 1 to length(valnam) do
case valnam[j] of
' ':
// allows {{helper1 helper2 value}} recursive calls
break;
',':
begin
// {{helper value,123,"constant"}}
p := pointer(valnam);
if j = 1 then
inc(p); // for {{helper ,"constant1","constant2",123}}
CsvToRawUtf8DynArray(p, names, ',', true);
// TODO: handle 123,"a,b,c"
valArr.InitFast;
for k := 0 to High(names) do
valArr.AddItem(GetVariantFromContext(names[k]));
valFound := true;
break;
end;
'<',
'>',
'=':
begin
// {{#if .=123}} -> {{#if .,"=",123}}
k := j + 1;
if valnam[k] in ['=', '>'] then
inc(k);
valArr.InitArray([
GetVariantFromContext(Copy(valnam, 1, j - 1)),
Copy(valnam, j, k - j),
GetVariantFromContext(Copy(valnam, k, maxInt))],
JSON_FAST_FLOAT);
valFound := true;
break;
end;
end;
if valFound then
valFree := true
else
GetVarDataFromContext(-1, valnam, val);
end;
end;
// call helper
if OwnValue <> nil then
begin
// result Value is owned by fTempProcessHelper[]
n := fContextCount + 4;
if length(fTempProcessHelper) < n then
SetLength(fTempProcessHelper, n);
OwnValue^ := @fTempProcessHelper[fContextCount - 1];
Helpers[helper].Event(variant(val), variant(OwnValue^^));
Value := OwnValue^^;
end
else
Helpers[helper].Event(variant(val), variant(Value));
if valFree then
VarClearProc(val);
result := msSinglePseudo;
end;
function TSynMustacheContext.GetHelperFromContext(ValueSpace: integer;
const ValueName: RawUtf8; var Value: TVarData;
OwnValue: PPVarData): TSynMustacheSectionType;
var
space, len, helper: PtrInt;
begin
space := ValueSpace;
if space < 0 then
space := PosExChar(' ', ValueName);
if space > 1 then
len := space - 1
else
begin
space := length(ValueName);
len := space;
end;
helper := TSynMustache.HelperFind(Helpers, pointer(ValueName), len);
if helper >= 0 then
result := ProcessHelper(ValueName, space, helper, Value, OwnValue)
else
result := msNothing;
end;
procedure TSynMustacheContext.CancelAll;
begin
fContextCount := 0;
fEscapeInvert := false;
fWriter.CancelAllAsNew;
if fTempProcessHelper <> nil then
VariantClearSeveral(pointer(fTempProcessHelper), length(fTempProcessHelper));
fReuse.UnLock;
end;
{ TSynMustacheContextVariant }
constructor TSynMustacheContextVariant.Create(Owner: TSynMustache;
WR: TJsonWriter; SectionMaxCount: integer; const aDocument: variant;
OwnWriter: boolean);
begin
inherited Create(Owner, WR, OwnWriter);
SetLength(fContext, SectionMaxCount + 4);
PushContext(TVarData(aDocument)); // weak copy
end;
function TSynMustacheContextVariant.Render(const aDoc: variant): RawUtf8;
begin
PushContext(TVarData(aDoc));
fOwner.RenderContext(self, 0, high(fOwner.fTags));
Writer.SetText(result);
CancelAll;
end;
procedure TSynMustacheContextVariant.PushContext(const aDoc: TVarData);
begin
if fContextCount >= length(fContext) then
// was roughtly set by SectionMaxCount
SetLength(fContext, fContextCount + 32);
with fContext[fContextCount] do
begin
Document := aDoc;
DocumentType := DocVariantType.FindSynVariantType(aDoc.VType);
ListCurrent := -1;
if DocumentType = nil then
ListCount := -1
else
begin
ListCount := DocumentType.IterateCount(aDoc, {GetObjectAsValues=}false);
if fContextCount = 0 then
ListCurrentDocument := aDoc; // allow {#.}...{/.} at first level
end;
end;
inc(fContextCount);
end;
function TSynMustacheContextVariant.GotoNextListItem: boolean;
begin
result := false;
if fContextCount > 0 then
with fContext[fContextCount - 1] do
begin
ListCurrentDocument.VType := varEmpty;
ListCurrentDocumentType := nil;
inc(ListCurrent);
if ListCurrent >= ListCount then
exit;
DocumentType.Iterate(ListCurrentDocument, Document, ListCurrent);
ListCurrentDocumentType := DocVariantType.FindSynVariantType(
ListCurrentDocument.VType);
result := true;
end;
end;
function TSynMustacheContextVariant.GetVarDataFromContext(ValueSpace: integer;
const ValueName: RawUtf8; var Value: TVarData): TSynMustacheSectionType;
var
i: PtrInt;
owned: PVarData;
begin
result := msNothing;
if PWord(ValueName)^ = ord('.') then
// {{.}} -> context = self
with fContext[fContextCount - 1] do
begin
if ListCount > 0 then
Value := ListCurrentDocument
else
Value := Document;
exit;
end;
// recursive search of {{value}}
for i := fContextCount - 1 downto 0 do
with fContext[i] do
if DocumentType <> nil then
if ListCount < 0 then
begin
// single item context
DocumentType.Lookup(Value, Document, pointer(ValueName), fPathDelim);
if Value.VType >= varNull then
exit;
end
else if PCardinal(ValueName)^ and $dfdfdfdf = (ord('-') and $df) +
ord('I') shl 8 + ord('N') shl 16 + ord('D') shl 24 then
begin
// {{-index}}
Value.VType := varInteger;
if ValueName[7] = '0' then
Value.VInteger := ListCurrent
else
Value.VInteger := ListCurrent + 1;
exit;
end
else if (ListCurrent < ListCount) and
(ListCurrentDocumentType <> nil) then
begin
ListCurrentDocumentType.Lookup(
Value, ListCurrentDocument, pointer(ValueName), fPathDelim);
if Value.VType >= varNull then
exit;
end;
// try {{helper value}} or {{helper}}
result := GetHelperFromContext(ValueSpace, ValueName, Value, @owned);
end;
procedure TSynMustacheContextVariant.AppendValue(ValueSpace: integer;
const ValueName: RawUtf8; UnEscape: boolean);
var
Value: TVarData;
begin
if fEscapeInvert then
UnEscape := not UnEscape;
GetVarDataFromContext(ValueSpace, ValueName, Value);
if Value.VType > varNull then
fWriter.AddVarData(@Value, not UnEscape);
end;
function SectionIsPseudo(const ValueName: RawUtf8; ListCount, ListCurrent: integer): boolean;
begin
result := ((ValueName = '-first') and
(ListCurrent = 0)) or
((ValueName = '-last') and
(ListCurrent = ListCount - 1)) or
((ValueName = '-odd') and
(ListCurrent and 1 = 0));
end;
function TSynMustacheContextVariant.AppendSection(ValueSpace: integer;
const ValueName: RawUtf8): TSynMustacheSectionType;
var
Value: TVarData;
c: cardinal;
void: boolean;
begin
result := msNothing;
if fContextCount = 0 then
exit;
if ValueName[1] = '-' then
with fContext[fContextCount - 1] do
if ListCount >= 0 then
begin
if SectionIsPseudo(ValueName, ListCount, ListCurrent) then
result := msSinglePseudo;
exit;
end;
result := GetVarDataFromContext(ValueSpace, ValueName, Value);
c := Value.VType;
void := (c <= varNull) or
((c = varBoolean) and
(Value.VWord = 0));
if (result <> msNothing) and // helper?
(c < varFirstCustom) then // simple helper values are not pushed
begin
if void then
result := msNothing;
exit;
end;
PushContext(Value);
if void then
// null or false value will not display the section
result := msNothing
else
with fContext[fContextCount - 1] do
if ListCount < 0 then
// single item
result := msSingle
else if ListCount = 0 then
// empty list will not display the section
result := msNothing
else
// non-empty list
result := msList;
end;
{ TSynMustacheContextData }
constructor TSynMustacheContextData.Create(Owner: TSynMustache;
WR: TJsonWriter; SectionMaxCount: integer; Value: pointer;
ValueRtti: TRttiCustom; OwnWriter: boolean);
begin
inherited Create(Owner, WR, OwnWriter);
fGetVarDataFromContextNeedsFree := true;
SetLength(fContext, SectionMaxCount + 4);