Repository navigation
Expand file tree
/
Copy pathTemplatePro.pas
More file actions
8196 lines (7789 loc) · 286 KB
/
Copy pathTemplatePro.pas
File metadata and controls
8196 lines (7789 loc) · 286 KB
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
// ***************************************************************************
//
// Copyright (c) 2016-2026 Daniele Teti
//
// https://github.com/danieleteti/templatepro
//
// ***************************************************************************
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ***************************************************************************
unit TemplatePro;
interface
uses
System.Generics.Collections,
System.Generics.Defaults,
System.Classes,
System.SysUtils,
System.TypInfo,
System.DateUtils,
System.RTTI,
System.Variants,
Data.DB,
ExprEvaluator,
TemplatePro.Types;
type
/// <summary>
/// Callback procedure for custom template loading.
/// Used to load templates from sources other than the file system (e.g., embedded resources, database, etc.)
/// </summary>
/// <param name="TemplateName">The name of the template as specified in the include/extends directive</param>
/// <param name="TemplateContent">Output parameter: set to the content of the template if found</param>
/// <param name="Handled">Output parameter: set to True if the template was loaded, False to fall back to file system</param>
TTProTemplateResolver = reference to procedure(
const TemplateName: string;
var TemplateContent: string;
var Handled: Boolean);
ITProCompiledTemplate = interface
['{0BE04DE7-6930-456B-86EE-BFD407BA6C46}']
function Render: String;
procedure ForEachToken(const TokenProc: TTokenWalkProc);
procedure ClearData;
procedure SetData(const Name: String; Value: TValue); overload;
procedure AddFilter(const FunctionName: string; const FunctionImpl: TTProTemplateFunction); overload;
procedure AddFilter(const FunctionName: string; const AnonFunctionImpl: TTProTemplateAnonFunction); overload;
procedure DumpToFile(const FileName: String);
procedure SaveToFile(const FileName: String);
function GetOnGetValue: TTProCompiledTemplateGetValueEvent;
procedure SetOnGetValue(const Value: TTProCompiledTemplateGetValueEvent);
property OnGetValue: TTProCompiledTemplateGetValueEvent read GetOnGetValue write SetOnGetValue;
function GetFormatSettings: PTProFormatSettings;
procedure SetFormatSettings(const Value: PTProFormatSettings);
property FormatSettings: PTProFormatSettings read GetFormatSettings write SetFormatSettings;
/// <summary>
/// Evaluates a complex expression using the ExpressionEvaluator engine.
/// The expression can reference template variables using their names.
/// Example: EvaluateExpression('price * qty * (1 - discount)')
/// </summary>
function EvaluateExpression(const Expression: string): TValue;
function GetOutputLineEnding: TLineEndingStyle;
procedure SetOutputLineEnding(const Value: TLineEndingStyle);
property OutputLineEnding: TLineEndingStyle read GetOutputLineEnding write SetOutputLineEnding;
function GetOnGetDynamicallyIncludedTemplate: TTProTemplateResolver;
procedure SetOnGetDynamicallyIncludedTemplate(const Value: TTProTemplateResolver);
/// <summary>
/// Optional callback for custom template loading during dynamic includes at runtime.
/// When set, this callback is invoked for runtime include directives like {{include @(expression)}}.
/// If the callback sets Handled to True, the provided content is used.
/// If Handled is False, the template falls back to loading from the file system.
/// </summary>
property OnGetDynamicallyIncludedTemplate: TTProTemplateResolver read GetOnGetDynamicallyIncludedTemplate write SetOnGetDynamicallyIncludedTemplate;
function GetIncludeRootPath: string;
procedure SetIncludeRootPath(const Value: string);
/// <summary>
/// Optional (empty by default). When set, dynamic includes loaded from the file system
/// must resolve to a file inside this folder, otherwise rendering fails.
/// </summary>
property IncludeRootPath: string read GetIncludeRootPath write SetIncludeRootPath;
/// <summary>
/// True when a dependency recorded at compile time (static include, extends, import - also nested) changed:
/// a file missing or with a different time or size, or a resolver-provided template whose version
/// (see TTProConfiguration.TemplateChanged) changed. Files are checked by time and size only.
/// The main template source is NOT a dependency: checking it is up to the caller.
/// </summary>
function IsStale: Boolean;
/// <summary>
/// The compiled form (the same format written by SaveToFile), to be loaded with TTProCompiledTemplate.CreateFromBytes.
/// </summary>
function SaveToBytes: TBytes;
end;
/// <summary>
/// One field of {{for f in model.@@fields}}: for a dataset its TField answers the same names, for an object
/// the engine creates one of these per property (and frees it). OnGetFieldMetadata can change it.
/// </summary>
TTProFieldMetadata = class
private
fFieldName: string;
fDisplayLabel: string;
fDataType: string;
fRequired: Boolean;
fReadOnly: Boolean;
fSize: Integer;
fVisible: Boolean;
fHidden: Boolean;
fValue: TValue;
public
property FieldName: string read fFieldName; // the property name
property DisplayLabel: string read fDisplayLabel write fDisplayLabel; // default: "CustomerName" -> "Customer name"
property DataType: string read fDataType write fDataType; // as TField.DataType: 'ftString', 'ftInteger', 'ftDate'...
property Required: Boolean read fRequired write fRequired; // default False
property ReadOnly: Boolean read fReadOnly write fReadOnly; // default: True when the property has no setter
property Size: Integer read fSize write fSize; // default 0 (unknown)
property Visible: Boolean read fVisible write fVisible; // default True
property Hidden: Boolean read fHidden write fHidden; // default False
property Value: TValue read fValue; // the current value (Nullable unwrapped: null -> empty)
end;
TTProCompiledTemplateEvent = reference to procedure(const TemplateProCompiledTemplate: ITProCompiledTemplate);
TTProOpenPush = record
Start: Integer; // position in the output buffer where the push content begins
StackName: string;
Once: Boolean;
end;
/// <summary>
/// {{push}}/{{stack}} state of one Render, shared with the dynamically included templates
/// </summary>
TTProStacks = class
private
fContents: TObjectDictionary<string, TList<string>>;
fPlaceholders: TList<TPair<Integer, string>>; // output position -> stack name
fOpenPushes: TStack<TTProOpenPush>;
public
constructor Create;
destructor Destroy; override;
procedure WriteInto(const aBuff: TStringBuilder);
end;
/// <summary>
/// A running macro: where its slots come from
/// </summary>
TTProSlotFrame = record
CallTokenIndex: Int64; // the {{call}} (or {{>}}) running the macro
CallerVariables: TTProVariables; // the slots are rendered in the caller's scope
CallerLoops: TObjectList<TLoopStackItem>; // ...with the caller's loop variables
ParentFrame: Integer; // the frame of the caller, -1 outside macros
end;
TTProCompiledTemplate = class(TInterfacedObject, ITProCompiledTemplate)
private
fLocaleFormatSettings: TFormatSettings;
fOutputLineEnding: TLineEndingStyle;
fTokens: TList<TToken>;
fVariables: TTProVariables;
fEncoding: TEncoding;
fDynamicIncludeCache: TDictionary<string, ITProCompiledTemplate>;
fTemplateFunctions: TDictionary<string, TTProTemplateFunction>;
fTemplateAnonFunctions: TDictionary<string, TTProTemplateAnonFunction>;
fMacros: TDictionary<string, TMacroDefinition>;
fLoopsStack: TObjectList<TLoopStackItem>;
fIncludeSavedVarsStack: TObjectList<TIncludeSavedVars>;
fAutoescapeStack: TStack<Boolean>;
fOnGetValue: TTProCompiledTemplateGetValueEvent;
fOnGetDynamicallyIncludedTemplate: TTProTemplateResolver;
fIncludeRootPath: string;
// Objects created by custom filters and stored with {{set}}: freed when Render ends
fOwnedObjects: TObjectList<TObject>;
// Macro calls + dynamic includes currently open (a dynamically included template starts from its parent's)
fRenderNestingDepth: Integer;
fStacks: TTProStacks; // set only while rendering
fSlotFrames: TList<TTProSlotFrame>; // one per running macro call
fCurrentSlotFrame: Integer; // the frame {{slot}} reads from, -1 outside macros
fExprEvaluator: TExprEvaluator;
function IsNullableType(const Value: PValue): Boolean;
procedure InitTemplateAnonFunctions; inline;
function PeekLoop: TLoopStackItem;
procedure PopLoop;
procedure PushLoop(const LoopStackItem: TLoopStackItem);
function LoopStackIsEmpty: Boolean;
function WalkThroughLoopStack(const VarName: String; out BaseVarName: String; out FullPath: String): Boolean;
constructor Create(Tokens: TList<TToken>);
procedure Error(const aMessage: String); overload;
procedure Error(const aMessage: String; const Params: array of const); overload;
function IsTruthy(const Value: TValue): Boolean;
function GetVarAsString(const Name: string): string;
function GetTValueVarAsString(const Value: PValue; out WasNull: Boolean; const VarName: string = ''): String;
function GetTValueWithNullableTypeAsString(const Value: PValue; out WasNull: Boolean; const VarName: string = ''): String;
function GetNullableTValueAsTValue(const Value: PValue; const VarName: string = ''): TValue;
function GetVarAsTValue(const aName: string): TValue;
function GetDataSetFieldAsTValue(const aDataSet: TDataSet; const FieldName: String): TValue;
function EvaluateIfExpressionAt(var Idx: Int64): Boolean;
function GetVariables: TTProVariables;
procedure SplitVariableName(const VariableWithMember: String; out VarName, VarMembers: String);
function ExecuteFilter(aFunctionName: string; var aParameters: TArray<TFilterParameter>; aValue: TValue;
const aVarNameWhereShoudBeApplied: String; out aIsCustomFilter: Boolean): TValue;
procedure ExecuteFilterTrackingOwnership(const aFilterName: string; var aParameters: TArray<TFilterParameter>;
var aValue: TValue; const aContextName: string; var aValueOwned: Boolean);
procedure ReleaseOwnedObjects;
procedure ResetRenderState;
procedure CheckParNumber(const aHowManyPars: Integer; const aParameters: TArray<TFilterParameter>); overload;
procedure CheckParNumber(const aMinParNumber, aMaxParNumber: Integer; const aParameters: TArray<TFilterParameter>); overload;
function GetPseudoVariable(const VarIterator: Integer; const PseudoVarName: String): TValue; overload;
function IsAnIterator(const VarName: String; out DataSourceName: String; out CurrentIterator: TLoopStackItem): Boolean;
function GetOnGetValue: TTProCompiledTemplateGetValueEvent;
function EvaluateValue(var Idx: Int64; out MustBeEncoded: Boolean; out ResultOwned: Boolean): TValue;
function EvaluateExpressionToken(var Idx: Int64; out MustBeEncoded: Boolean; out ResultOwned: Boolean): TValue;
procedure ApplyFilters(var Idx: Int64; var Value: TValue; FilterCount: Int64; const ContextName: string;
out ValueOwned: Boolean; out ValueIsHTML: Boolean);
function IsCustomFilter(const aFilterName: string): Boolean;
function ResolveFilterParameter(const aToken: TToken): TFilterParameter;
function GetParameterValue(const aParameter: TFilterParameter): TValue;
function ValueAsString(const aValue: TValue): string;
function OutputString(const aValue: TValue): string;
function MemberValue(const aModel: TValue; const aName: string): TValue;
function IsObjectForFields(const aExpression: string; out aObject: TValue): Boolean;
function ObjectFieldsMetadata(const aObject: TObject): TObjectList<TTProFieldMetadata>;
function ExecuteListAndTextFilter(const aFunctionName: string; var aParameters: TArray<TFilterParameter>;
const aValue: TValue; out aResult: TValue): Boolean;
procedure SetOnGetValue(const Value: TTProCompiledTemplateGetValueEvent);
procedure DoOnGetValue(const DataSource, Members: string; var Value: TValue; var Handled: Boolean);
function GetFormatSettings: PTProFormatSettings;
procedure SetFormatSettings(const Value: PTProFormatSettings);
class procedure InternalDumpToFile(const FileName: String; const aTokens: TList<TToken>);
function ComparandOperator(const aComparandType: TComparandType; const aValue: TValue; const aParameters: TArray<TFilterParameter>;
const aLocaleFormatSettings: TFormatSettings): TValue;
procedure RegisterMacro(const TokenIndex: Int64);
procedure ExecuteMacro(const CallTokenIndex: Int64; const aBuff: TStringBuilder);
procedure ExecuteMacroBody(const CallTokenIndex: Int64; const aBuff: TStringBuilder);
procedure RenderTo(const aBuff: TStringBuilder; const aStacks: TTProStacks);
procedure RenderRange(const aBuff: TStringBuilder; const aFrom, aTo: Int64);
function RenderSlot(const aSlotIdx: Int64; const aBuff: TStringBuilder): Int64;
function FindSlotContent(const aCallIdx: Int64; const aSlotName: string; out aFrom, aTo: Int64): Boolean;
function IsBlankRange(const aFrom, aTo: Int64): Boolean;
function SlotsInfo(const aCallIdx: Int64): TObject; // a TJDOJsonObject
function ResolveTokenName(const aToken: TToken): string;
procedure BeginPush(const aIdx: Int64; const aBuff: TStringBuilder);
procedure EndPush(const aBuff: TStringBuilder);
procedure AddStackPlaceholder(const aIdx: Int64; const aBuff: TStringBuilder);
function MacroArgumentValue(const aParameter: TFilterParameter): TValue;
function MacroArgument(const aTokenIdx: Int64; const aParameter: TFilterParameter; var aOwned: TArray<TObject>): TValue;
function LastFilterToken(const aIdx: Int64): Int64;
procedure ProcessSetToken(var Idx: Int64);
function SelectSwitchBranch(const aSwitchIdx: Int64): Int64;
procedure InitRangeLoop(const aLoop: TLoopStackItem);
function TokenToFilterParameter(const aToken: TToken): TFilterParameter;
function ValueToFilterParameter(const aValue: TValue): TFilterParameter;
function ExecuteStringFilter(const aFunctionName: string; var aParameters: TArray<TFilterParameter>;
const aValue: TValue; const aExecuteAsFilterOnAValue: Boolean; out aResult: TValue): Boolean;
function ExecuteDateFilter(const aFunctionName: string; var aParameters: TArray<TFilterParameter>;
const aValue: TValue; const aVarNameWhereShoudBeApplied: String; out aResult: TValue): Boolean;
function GetExprEvaluator: TExprEvaluator;
function TValueToVariant(const Value: TValue): Variant;
function VariantToTValue(const Value: Variant): TValue;
function GetFieldProperty(const AField: TField; const PropName: string): TValue;
function EvaluateDataSetFieldMeta(const DataSetVarName, FieldMetaInfo: string): TValue;
function GetOutputLineEnding: TLineEndingStyle;
procedure SetOutputLineEnding(const Value: TLineEndingStyle);
function GetLineEndingString: string;
function GetOnGetDynamicallyIncludedTemplate: TTProTemplateResolver;
procedure SetOnGetDynamicallyIncludedTemplate(const Value: TTProTemplateResolver);
function GetIncludeRootPath: string;
procedure SetIncludeRootPath(const Value: string);
public
function EvaluateExpression(const Expression: string): TValue;
destructor Destroy; override;
function Render: String;
function IsStale: Boolean;
procedure ForEachToken(const TokenProc: TTokenWalkProc);
procedure ClearData;
procedure SaveToFile(const FileName: String);
function SaveToBytes: TBytes;
class function CreateFromFile(const FileName: String): ITProCompiledTemplate;
/// <summary>
/// A new, independent instance from the output of SaveToBytes. No file system access.
/// </summary>
class function CreateFromBytes(const aBytes: TBytes): ITProCompiledTemplate;
procedure SetData(const Name: String; Value: TValue); overload;
procedure AddFilter(const FunctionName: string; const FunctionImpl: TTProTemplateFunction); overload;
procedure AddFilter(const FunctionName: string; const AnonFunctionImpl: TTProTemplateAnonFunction); overload;
procedure DumpToFile(const FileName: String);
property FormatSettings: PTProFormatSettings read GetFormatSettings write SetFormatSettings;
property OnGetValue: TTProCompiledTemplateGetValueEvent read GetOnGetValue write SetOnGetValue;
property OutputLineEnding: TLineEndingStyle read GetOutputLineEnding write SetOutputLineEnding;
property OnGetDynamicallyIncludedTemplate: TTProTemplateResolver read GetOnGetDynamicallyIncludedTemplate write SetOnGetDynamicallyIncludedTemplate;
end;
TTProCompiler = class
strict private
fOptions: TTProCompilerOptions;
fInputString: string;
fCharIndex: Int64;
fCurrentLine: Integer;
fEncoding: TEncoding;
fCurrentFileName: String;
fLastMatchedLineBreakLength: Integer;
fInheritanceChain: TList<string>;
fIncludeChain: TList<string>; // files being compiled, from the root down to the current one
fStripNextLeadingWS: Boolean; // For whitespace control: -}} strips leading WS from next content
fOnGetIncludedTemplate: TTProTemplateResolver;
// {{import}} namespace -> library full path, shared with the files included in the same template
fNamespaces: TDictionary<string, string>;
fOwnedNamespaces: TDictionary<string, string>;
// ttDependency tokens of the template being compiled, shared with the compilers of its includes, layouts and libraries
fDependencies: TList<TToken>;
fOwnedDependencies: TList<TToken>;
procedure AddDependency(const aName, aKind: string; const aRef1, aRef2: Int64);
procedure ImportLibrary(const aLibraryName, aAlias: string; const aTokens: TList<TToken>; const aFileNameRefPath: string);
function MatchLineBreak: Boolean;
function MatchStartTag: Boolean;
function MatchEndTag: Boolean;
function MatchVariable(var aIdentifier: string): Boolean;
function MatchFilterParamValue(var aParamValue: TFilterParameter): Boolean;
function MatchSymbol(const aSymbol: string): Boolean;
function MatchExpression(out aExpression: string): Boolean;
function MatchRange(out aRangeExpression: string): Boolean;
function MatchNameArgument(out aName, aKind: string): Boolean;
function MatchSpace: Boolean;
function MatchString(out aStringValue: string): Boolean;
procedure InternalMatchFilter(lIdentifier: String; var lStartVerbatim: Int64; const CurrToken: TTokenType; aTokens: TList<TToken>;
const lRef2: Integer);
function GetFunctionParameters(const aStopAtNamedArg: Boolean = False): TArray<TFilterParameter>;
function GetMacroParameters(out aNames: TArray<string>; out aFilters: TArray<TArray<TFilterInfo>>): TArray<TFilterParameter>;
procedure AddMacroParameterTokens(aTokens: TList<TToken>; const aMacroTokenIdx: Integer; const aParamTokens: TArray<TToken>;
const aFilters: TArray<TArray<TFilterInfo>>);
function CreateFilterParameterToken(const FilterParameter: PFilterParameter): TToken;
procedure Error(const aMessage: string);
function Step: Char;
function CurrentChar: Char;
function GetSubsequentText: String;
procedure InternalCompileIncludedTemplate(const aTemplate: string; const aTokens: TList<TToken>; const aFileNameRefPath: String;
const aCompilerOptions: TTProCompilerOptions);
procedure ProcessJumps(const aTokens: TList<TToken>);
procedure Compile(const aTemplate: string; const aTokens: TList<TToken>; const aFileNameRefPath: String); overload;
constructor Create(const aEncoding: TEncoding; const aOptions: TTProCompilerOptions = []); overload;
procedure MatchFilters(lVarName: string; var lFilters: TArray<TFilterInfo>; const aStopAtNamedArg: Boolean = False);
procedure AddFilterTokens(aTokens: TList<TToken>; const aFilters: TArray<TFilterInfo>);
function LoadTemplateSource(const aTemplateName: string; const aFullPath: string): string;
public
destructor Destroy; override;
function Compile(const aTemplate: string; const aFileNameRefPath: String = ''): ITProCompiledTemplate; overload;
/// <summary>
/// Compiles a template directly from a string.
/// Useful for templates that don't come from files (e.g., from database, strings, etc.)
/// </summary>
/// <param name="aTemplateString">The template source code as a string</param>
/// <returns>A compiled template ready for data binding and rendering</returns>
function CompileFromString(const aTemplateString: string): ITProCompiledTemplate;
constructor Create(aEncoding: TEncoding = nil); overload;
class function CompileAndRender(const aTemplate: string; const VarNames: TArray<String>;
const VarValues: TArray<TValue>; const aFileNameRefPath: String = ''): String;
/// <summary>
/// Optional callback for custom template loading.
/// When set, this callback is invoked for include and extends directives.
/// If the callback returns True, the provided content is used.
/// If it returns False, the compiler falls back to loading from the file system.
/// </summary>
property OnGetIncludedTemplate: TTProTemplateResolver read fOnGetIncludedTemplate write fOnGetIncludedTemplate;
end;
ITProWrappedList = interface
['{C1963FBF-1E42-4E2A-A17A-27F3945F13ED}']
function GetItem(const AIndex: Integer): TObject;
procedure Add(const AObject: TObject);
function Count: Integer;
procedure Clear;
function IsWrappedList: Boolean; overload;
function ItemIsObject(const AIndex: Integer; out aValue: TValue): Boolean;
end;
TTProFieldMetadataEvent = reference to procedure(const aObject: TObject; const aPropertyName: string;
const aMetadata: TTProFieldMetadata);
TTProConfiguration = class sealed
private
class var fOnContextConfiguration: TTProCompiledTemplateEvent;
class var fOnGetFieldMetadata: TTProFieldMetadataEvent;
class var fOnGetTemplate: TTProTemplateResolver;
class var fTemplateVersions: TDictionary<string, Int64>; // guarded by TMonitor
class constructor Create;
class destructor Destroy;
protected
class procedure RegisterHandlers(const TemplateProCompiledTemplate: ITProCompiledTemplate);
public
class property OnContextConfiguration: TTProCompiledTemplateEvent read fOnContextConfiguration write fOnContextConfiguration;
/// <summary>
/// Optional global resolver for static includes, extends, imports (compile time) and dynamic includes (render time),
/// usable where the compiler is not accessible. It is asked after the instance resolver
/// (TTProCompiler.OnGetIncludedTemplate / OnGetDynamicallyIncludedTemplate) and before the file system.
/// Set it at startup: it is not synchronized.
/// </summary>
class property OnGetTemplate: TTProTemplateResolver read fOnGetTemplate write fOnGetTemplate;
/// <summary>
/// Called once per property when {{for f in obj.@@fields}} iterates an object (not a dataset): it can change
/// DisplayLabel, DataType, Required, ReadOnly, Size, Visible, Hidden. Set it at startup: it is not synchronized.
/// </summary>
class property OnGetFieldMetadata: TTProFieldMetadataEvent read fOnGetFieldMetadata write fOnGetFieldMetadata;
/// <summary>
/// Call it when a template served by a resolver changed (e.g. in a database): the compiled templates
/// depending on that name become stale (ITProCompiledTemplate.IsStale). Names are case-insensitive. Thread-safe.
/// </summary>
class procedure TemplateChanged(const Name: string);
class function GetTemplateVersion(const Name: string): Int64;
end;
function HTMLEncode(s: string): string;
function HandleTemplateSectionStateMachine(const aTokenValue1: String; var aTemplateSectionType: TTProTemplateSectionType;
out aErrorMessage: String): Boolean;
function GetTValueFromPath(const aObject: TObject; FullPropertyPath: String): TValue;
implementation
uses
System.StrUtils, System.IOUtils, System.NetEncoding, System.Math, System.Character, System.RegularExpressions,
JsonDataObjects, MVCFramework.Nullables, Data.FmtBCD, Data.SqlTimSt;
const
MAX_RENDER_NESTING = 64; // recursion through macros and dynamic includes, e.g. a tree 64 levels deep
Sign = ['-', '+'];
Numbers = ['0' .. '9'];
SignAndNumbers = Sign + Numbers;
IdenfierAllowedFirstChars = ['a' .. 'z', 'A' .. 'Z', '_', '@'];
IdenfierAllowedChars = ['a' .. 'z', 'A' .. 'Z', '_'] + Numbers;
ValueAllowedChars = IdenfierAllowedChars + [' ', '-', '+', '*', '.', '@', '/', '\']; // maybe a lot others
START_TAG = '{{';
END_TAG = '}}';
RANGE_PREFIX = 'range(';
RANGE_ARG_SEPARATOR = #1; // between the arguments of a compiled range(...)
type
TTProRTTIUtils = class sealed
public
class function GetProperty(AObject: TObject; const APropertyName: string): TValue;
class function ObjectToJSONString(AObject: TObject): string;
end;
TTProDuckTypedList = class(TInterfacedObject, ITProWrappedList)
private
FObjectAsDuck: TObject;
FObjType: TRttiType;
FAddMethod: TRttiMethod;
FClearMethod: TRttiMethod;
FCountProperty: TRttiProperty;
FGetItemMethod: TRttiMethod;
FGetCountMethod: TRttiMethod;
FIsWrappedList: Boolean;
function HookListMethods(const aObjType: TRttiType): Boolean;
protected
procedure Add(const AObject: TObject);
procedure Clear;
function ItemIsObject(const AIndex: Integer; out aValue: TValue): Boolean;
public
constructor Create(const AObjectAsDuck: TObject); overload;
constructor Create(const AInterfaceAsDuck: IInterface); overload;
function IsWrappedList: Boolean; overload;
function Count: Integer;
procedure GetItemAsTValue(const AIndex: Integer; out aValue: TValue);
function GetItem(const AIndex: Integer): TObject;
class function CanBeWrappedAsList(const AObjectAsDuck: TObject): Boolean; overload; static;
class function CanBeWrappedAsList(const AObjectAsDuck: TObject; out AMVCList: ITProWrappedList): Boolean; overload; static;
class function CanBeWrappedAsList(const AInterfaceAsDuck: IInterface): Boolean; overload; static;
class function Wrap(const AObjectAsDuck: TObject): ITProWrappedList; static;
end;
var
GlContext: TRttiContext;
function WrapAsList(const AObject: TObject): ITProWrappedList;
begin
Result := TTProDuckTypedList.Wrap(AObject);
end;
function GetFileStamp(const aFileName: string; out aTime, aSize: Int64): Boolean;
// last write time (as its bits) and size, without opening the file
var
lSearchRec: TSearchRec;
lDateTime: TDateTime;
begin
Result := FindFirst(aFileName, faAnyFile, lSearchRec) = 0;
if not Result then
Exit;
try
lDateTime := lSearchRec.TimeStamp;
aTime := PInt64(@lDateTime)^;
aSize := lSearchRec.Size;
finally
FindClose(lSearchRec);
end;
end;
procedure FunctionError(const aFunctionName, aErrMessage: string);
begin
raise ETProRenderException.Create(Format('[%1:s] %0:s (error in filter call for function [%1:s])', [aErrMessage, aFunctionName]))
at ReturnAddress;
end;
function TTProCompiledTemplate.ComparandOperator(const aComparandType: TComparandType; const aValue: TValue;
const aParameters: TArray<TFilterParameter>; const aLocaleFormatSettings: TFormatSettings): TValue;
var
lInt64Value: Int64;
lStrValue: string;
lExtendedValue: Extended;
lValue, lTmp: TValue;
function GetComparandResultStr(const aComparandType: TComparandType; const aLeftValue, aRightValue: String): TValue;
begin
case aComparandType of
ctEQ:
Result := aLeftValue = aRightValue;
ctNE:
Result := aLeftValue <> aRightValue;
ctGT:
Result := aLeftValue > aRightValue;
ctGE:
Result := aLeftValue >= aRightValue;
ctLT:
Result := aLeftValue < aRightValue;
ctLE:
Result := aLeftValue <= aRightValue;
else
raise ETProRenderException.Create('Invalid Comparand Type: ' + TRttiEnumerationType.GetName<TComparandType>(aComparandType));
end;
end;
begin
if Length(aParameters) <> 1 then
FunctionError(TRttiEnumerationType.GetName<TComparandType>(aComparandType), 'expected 1 parameter');
if aValue.IsEmpty then
begin
Result := False;
Exit;
end;
case aValue.TypeInfo.Kind of
tkInteger, tkEnumeration, tkInt64:
begin
if aParameters[0].ParType = fptString then
begin
raise ETProRenderException.Create('Invalid type for comparand');
end;
if aParameters[0].ParType = fptFloat then
Exit(ComparandOperator(aComparandType, TValue.From<Extended>(aValue.AsOrdinal), aParameters, aLocaleFormatSettings));
if aParameters[0].ParType = fptInteger then
begin
lInt64Value := aParameters[0].ParIntValue
end
else
begin
lTmp := GetVarAsTValue(aParameters[0].ParStrText);
if IsNullableType(@lTmp) then
begin
lTmp := GetNullableTValueAsTValue(@lTmp);
if lTmp.IsEmpty then
begin
Exit(False);
end;
end;
lInt64Value := lTmp.AsInt64;
end;
case aComparandType of
ctEQ:
Result := aValue.AsInt64 = lInt64Value;
ctNE:
Result := aValue.AsInt64 <> lInt64Value;
ctGT:
Result := aValue.AsInt64 > lInt64Value;
ctGE:
Result := aValue.AsInt64 >= lInt64Value;
ctLT:
Result := aValue.AsInt64 < lInt64Value;
ctLE:
Result := aValue.AsInt64 <= lInt64Value;
else
raise ETProRenderException.Create('Invalid Comparand Type: ' + TRttiEnumerationType.GetName<TComparandType>(aComparandType));
end;
end;
tkFloat:
begin
if aValue.TypeInfo.Name = 'TDateTime' then
begin
lStrValue := DateTimeToStr(aValue.AsExtended, aLocaleFormatSettings);
case aParameters[0].ParType of
fptString:
begin
Result := GetComparandResultStr(aComparandType, lStrValue, aParameters[0].ParStrText);
end;
fptVariable:
begin
lValue := GetVarAsTValue(aParameters[0].ParStrText);
Result := GetComparandResultStr(aComparandType, lStrValue, lValue.AsString);
end;
else
Error('Invalid parameter type for ' + TRttiEnumerationType.GetName<TComparandType>(aComparandType));
end;
end
else if aValue.TypeInfo.Name = 'TDate' then
begin
lStrValue := DateToStr(aValue.AsExtended, aLocaleFormatSettings);
case aParameters[0].ParType of
fptString:
begin
Result := GetComparandResultStr(aComparandType, lStrValue, aParameters[0].ParStrText)
end;
fptVariable:
begin
lValue := GetVarAsTValue(aParameters[0].ParStrText);
Result := GetComparandResultStr(aComparandType, lStrValue, lValue.AsString);
end;
else
Error('Invalid parameter type for ' + TRttiEnumerationType.GetName<TComparandType>(aComparandType));
end;
end
else
begin
lExtendedValue := 0;
case aParameters[0].ParType of
fptInteger:
begin
lExtendedValue := aParameters[0].ParIntValue;
end;
fptFloat:
begin
lExtendedValue := aParameters[0].ParFloatValue;
end;
fptVariable:
begin
lValue := GetVarAsTValue(aParameters[0].ParStrText);
lExtendedValue := lValue.AsExtended;
end;
else
Error('Invalid parameter type for ' + TRttiEnumerationType.GetName<TComparandType>(aComparandType));
end;
case aComparandType of
ctEQ:
Result := aValue.AsExtended = lExtendedValue;
ctNE:
Result := aValue.AsExtended <> lExtendedValue;
ctGT:
Result := aValue.AsExtended > lExtendedValue;
ctGE:
Result := aValue.AsExtended >= lExtendedValue;
ctLT:
Result := aValue.AsExtended < lExtendedValue;
ctLE:
Result := aValue.AsExtended <= lExtendedValue;
else
raise ETProRenderException.Create('Invalid Comparand Type: ' + TRttiEnumerationType.GetName<TComparandType>(aComparandType));
end
end;
end;
else
begin
case aParameters[0].ParType of
fptString:
begin
Result := GetComparandResultStr(aComparandType, aValue.AsString, aParameters[0].ParStrText)
end;
fptInteger:
begin
Result := GetComparandResultStr(aComparandType, aValue.AsString, aParameters[0].ParIntValue.ToString)
end;
fptVariable:
begin
lValue := GetVarAsTValue(aParameters[0].ParStrText);
Result := GetComparandResultStr(aComparandType, aValue.AsString, lValue.AsString);
end;
else
Error('Invalid parameter type for ' + TRttiEnumerationType.GetName<TComparandType>(aComparandType));
end;
end;
end;
end;
{ TParser }
procedure TTProCompiledTemplate.AddFilter(const FunctionName: string; const FunctionImpl: TTProTemplateFunction);
begin
fTemplateFunctions.Add(FunctionName.ToLower, FunctionImpl);
end;
{ Cardinal (and other 32-bit unsigned types) and UInt64 must not be read with
AsInteger/AsInt64: values above the signed maximum would come out negative. }
function IsUnsignedInteger(const aTypeInfo: PTypeInfo): Boolean;
begin
Result := (aTypeInfo <> nil) and (aTypeInfo^.Kind = tkInteger) and
(GetTypeData(aTypeInfo)^.OrdType = otULong);
end;
function IsUnsignedInt64(const aTypeInfo: PTypeInfo): Boolean;
begin
// for an unsigned 64-bit type the range stored as Int64 is 0..-1
Result := (aTypeInfo <> nil) and (aTypeInfo^.Kind = tkInt64) and
(GetTypeData(aTypeInfo)^.MinInt64Value > GetTypeData(aTypeInfo)^.MaxInt64Value);
end;
function TTProCompiledTemplate.GetDataSetFieldAsTValue(const aDataSet: TDataSet; const FieldName: String): TValue;
var
lField: TField;
begin
lField := aDataSet.FindField(FieldName);
if not Assigned(lField) then
begin
Exit(TValue.Empty);
end;
case lField.DataType of
ftInteger, ftSmallInt, ftWord, ftShortint, ftByte:
Result := lField.AsInteger;
ftLargeint, ftAutoInc:
Result := lField.AsLargeInt;
{$IF CompilerVersion >= 37} // ftLargeUint and TField.AsLargeUInt exist since Delphi 13
ftLargeUint:
Result := lField.AsLargeUInt;
{$ENDIF}
ftLongWord:
Result := lField.AsLongWord;
ftFloat:
Result := lField.AsFloat;
ftSingle:
Result := lField.AsSingle;
ftExtended:
Result := lField.AsExtended;
ftCurrency:
Result := lField.AsCurrency;
ftString, ftWideString, ftMemo, ftWideMemo, ftGuid, ftFixedChar, ftFixedWideChar:
Result := lField.AsWideString;
ftDate:
Result := TDate(Trunc(lField.AsDateTime));
ftDateTime, ftTimeStamp:
Result := lField.AsDateTime;
ftTimeStampOffset:
Result := TValue.From<TSQLTimeStampOffset>(lField.AsSQLTimeStampOffset);
ftTime:
Result := lField.AsDateTime;
ftBoolean:
Result := lField.AsBoolean;
ftFMTBcd, ftBcd:
Result := TValue.From<TBCD>(lField.AsBCD);
else
Error('Invalid data type for field "%s": %s', [FieldName, TRttiEnumerationType.GetName<TFieldType>(lField.DataType)]);
end;
end;
function TTProCompiledTemplate.GetFormatSettings: PTProFormatSettings;
begin
Result := @fLocaleFormatSettings;
end;
function TTProCompiledTemplate.GetOutputLineEnding: TLineEndingStyle;
begin
Result := fOutputLineEnding;
end;
procedure TTProCompiledTemplate.SetOutputLineEnding(const Value: TLineEndingStyle);
begin
fOutputLineEnding := Value;
end;
function TTProCompiledTemplate.GetLineEndingString: string;
begin
case fOutputLineEnding of
lesLF: Result := #10;
lesCRLF: Result := #13#10;
lesCR: Result := #13;
lesNative: Result := sLineBreak;
else
Result := sLineBreak;
end;
end;
function TTProCompiledTemplate.GetOnGetDynamicallyIncludedTemplate: TTProTemplateResolver;
begin
Result := fOnGetDynamicallyIncludedTemplate;
end;
procedure TTProCompiledTemplate.SetOnGetDynamicallyIncludedTemplate(const Value: TTProTemplateResolver);
begin
fOnGetDynamicallyIncludedTemplate := Value;
end;
function TTProCompiledTemplate.GetIncludeRootPath: string;
begin
Result := fIncludeRootPath;
end;
procedure TTProCompiledTemplate.SetIncludeRootPath(const Value: string);
begin
fIncludeRootPath := Value;
end;
function TTProCompiledTemplate.GetNullableTValueAsTValue(const Value: PValue; const VarName: string): TValue;
var
lNullableInt32: NullableInt32;
lNullableUInt32: NullableUInt32;
lNullableInt16: NullableInt16;
lNullableUInt16: NullableUInt16;
lNullableInt64: NullableInt64;
lNullableUInt64: NullableUInt64;
lNullableCurrency: NullableCurrency;
lNullableBoolean: NullableBoolean;
lNullableTDate: NullableTDate;
lNullableTTime: NullableTTime;
lNullableTDateTime: NullableTDateTime;
lNullableString: NullableString;
begin
Result := TValue.Empty;
if Value.IsEmpty then
begin
Exit;
end;
if Value.TypeInfo.Kind = tkRecord then
begin
if Value.TypeInfo = TypeInfo(NullableInt32) then
begin
lNullableInt32 := Value.AsType<NullableInt32>;
if lNullableInt32.HasValue then
Exit(lNullableInt32.Value);
end
else if Value.TypeInfo = TypeInfo(NullableUInt32) then
begin
lNullableUInt32 := Value.AsType<NullableUInt32>;
if lNullableUInt32.HasValue then
Exit(lNullableUInt32.Value);
end
else if Value.TypeInfo = TypeInfo(NullableInt16) then
begin
lNullableInt16 := Value.AsType<NullableInt16>;
if lNullableInt16.HasValue then
Exit(lNullableInt16.Value);
end
else if Value.TypeInfo = TypeInfo(NullableUInt16) then
begin
lNullableUInt16 := Value.AsType<NullableUInt16>;
if lNullableUInt16.HasValue then
Exit(lNullableUInt16.Value);
end
else if Value.TypeInfo = TypeInfo(NullableInt64) then
begin
lNullableInt64 := Value.AsType<NullableInt64>;
if lNullableInt64.HasValue then
Exit(lNullableInt64.Value);
end
else if Value.TypeInfo = TypeInfo(NullableUInt64) then
begin
lNullableUInt64 := Value.AsType<NullableUInt64>;
if lNullableUInt64.HasValue then
Exit(lNullableUInt64.Value);
end
else if Value.TypeInfo = TypeInfo(NullableString) then
begin
lNullableString := Value.AsType<NullableString>;
if lNullableString.HasValue then
Exit(lNullableString.Value);
end
else if Value.TypeInfo = TypeInfo(NullableCurrency) then
begin
lNullableCurrency := Value.AsType<NullableCurrency>;
if lNullableCurrency.HasValue then
Exit(lNullableCurrency.Value);
end
else if Value.TypeInfo = TypeInfo(NullableBoolean) then
begin
lNullableBoolean := Value.AsType<NullableBoolean>;
if lNullableBoolean.HasValue then
Exit(lNullableBoolean.Value);
end
else if Value.TypeInfo = TypeInfo(NullableTDate) then
begin
lNullableTDate := Value.AsType<NullableTDate>;
if lNullableTDate.HasValue then
Exit(lNullableTDate.Value);
end
else if Value.TypeInfo = TypeInfo(NullableTTime) then
begin
lNullableTTime := Value.AsType<NullableTTime>;
if lNullableTTime.HasValue then
Exit(lNullableTTime.Value);
end
else if Value.TypeInfo = TypeInfo(NullableTDateTime) then
begin
lNullableTDateTime := Value.AsType<NullableTDateTime>;
if lNullableTDateTime.HasValue then
Exit(lNullableTDateTime.Value);
end
else
begin
raise ETProException.Create('Unsupported type for variable "' + VarName + '"');
end;
end
else
begin
Result := Value^;
end;
end;
function TTProCompiledTemplate.GetOnGetValue: TTProCompiledTemplateGetValueEvent;
begin
Result := fOnGetValue;
end;
function TTProCompiledTemplate.GetPseudoVariable(const VarIterator: Integer; const PseudoVarName: String): TValue;
var
lLoopItem: TLoopStackItem;
begin
if PseudoVarName = '@@index' then
begin
Result := VarIterator + 1;
end
else if PseudoVarName = '@@odd' then
begin
Result := (VarIterator + 1) mod 2 > 0;
end
else if PseudoVarName = '@@even' then
begin
Result := (VarIterator + 1) mod 2 = 0;
end
else if PseudoVarName = '@@first' then
begin
Result := VarIterator = 0;
end
else if PseudoVarName = '@@last' then
begin
lLoopItem := PeekLoop;
if Assigned(lLoopItem) and (lLoopItem.TotalCount > 0) then
Result := VarIterator = lLoopItem.TotalCount - 1
else
Result := False;
end
else
begin
Result := TValue.Empty;
end;
end;
procedure ParseJSONArrayPath(const aPath: String; out aIndex: Integer; out aRemainingPath: String);
var
lCloseBracketPos: Integer;
begin
// Path format: [index].property.subproperty or [index]
// Example: [0].devices or [0].car.brand
aIndex := -1;
aRemainingPath := '';
if not aPath.StartsWith('[') then
Exit;
// Extract index from [index]
lCloseBracketPos := aPath.IndexOf(']');
if lCloseBracketPos < 0 then
Exit;
aIndex := StrToIntDef(aPath.Substring(1, lCloseBracketPos - 1), -1);
// Get remaining path after ]
aRemainingPath := aPath.Substring(lCloseBracketPos + 1);
if aRemainingPath.StartsWith('.') then
aRemainingPath := aRemainingPath.Substring(1);
end;
function TTProCompiledTemplate.GetTValueVarAsString(const Value: PValue; out WasNull: Boolean; const VarName: string): String;
var
lIsObject: Boolean;
lAsObject: TObject;
lVarName: string;
lVarMember: string;
lTmp: TValue;
lIsNull: Boolean;
begin
if Value.IsEmpty then
begin
Exit('');
end;
lIsObject := False;
lAsObject := nil;
if Value.IsObject then
begin
lIsObject := True;
lAsObject := Value.AsObject;
end;
if lIsObject then
begin