summaryrefslogtreecommitdiff
path: root/packages/fcl-mustache/examples
diff options
context:
space:
mode:
Diffstat (limited to 'packages/fcl-mustache/examples')
-rw-r--r--packages/fcl-mustache/examples/README.txt27
-rw-r--r--packages/fcl-mustache/examples/demo1.lpi57
-rw-r--r--packages/fcl-mustache/examples/demo1.lpr42
-rw-r--r--packages/fcl-mustache/examples/demo2.lpi57
-rw-r--r--packages/fcl-mustache/examples/demo2.lpr48
-rw-r--r--packages/fcl-mustache/examples/family.csv7
-rw-r--r--packages/fcl-mustache/examples/family.json10
-rw-r--r--packages/fcl-mustache/examples/family.tmpl22
-rw-r--r--packages/fcl-mustache/examples/mustache.lpi57
-rw-r--r--packages/fcl-mustache/examples/mustache.lpr207
10 files changed, 534 insertions, 0 deletions
diff --git a/packages/fcl-mustache/examples/README.txt b/packages/fcl-mustache/examples/README.txt
new file mode 100644
index 0000000000..b46598b216
--- /dev/null
+++ b/packages/fcl-mustache/examples/README.txt
@@ -0,0 +1,27 @@
+demo1 sample program:
+
+Demonstrates the most basic use of the mustache parser
+
+demo2 sample program:
+
+Demonstrates the use of the mustache parser with a CSV dataset
+
+
+mustache example program:
+
+Can be used to load a template and data, and process the result.
+Output to standard output or file.
+The template and JSON value can be loaded from file (using @filename),
+or their value can be specified directly on the command-line.
+
+Example usage:
+
+Load template from family.tmpl file, data from family.json file:
+
+./mustache -d title="my family" -t @family.tmpl -j @family.json
+
+Load template from family.tmpl file, data from family.csv file:
+
+./mustache -d title="my family" -t @family.tmpl -c family.csv
+
+Use of expressions can be enabled with the -e switch.
diff --git a/packages/fcl-mustache/examples/demo1.lpi b/packages/fcl-mustache/examples/demo1.lpi
new file mode 100644
index 0000000000..6e03c0c1fd
--- /dev/null
+++ b/packages/fcl-mustache/examples/demo1.lpi
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<CONFIG>
+ <ProjectOptions>
+ <Version Value="12"/>
+ <General>
+ <Flags>
+ <MainUnitHasCreateFormStatements Value="False"/>
+ <MainUnitHasTitleStatement Value="False"/>
+ <MainUnitHasScaledStatement Value="False"/>
+ </Flags>
+ <SessionStorage Value="InProjectDir"/>
+ <Title Value="demo1"/>
+ <UseAppBundle Value="False"/>
+ <ResourceType Value="res"/>
+ </General>
+ <BuildModes>
+ <Item Name="Default" Default="True"/>
+ </BuildModes>
+ <PublishOptions>
+ <Version Value="2"/>
+ <UseFileFilters Value="True"/>
+ </PublishOptions>
+ <RunParams>
+ <FormatVersion Value="2"/>
+ </RunParams>
+ <Units>
+ <Unit>
+ <Filename Value="demo1.lpr"/>
+ <IsPartOfProject Value="True"/>
+ </Unit>
+ </Units>
+ </ProjectOptions>
+ <CompilerOptions>
+ <Version Value="11"/>
+ <Target>
+ <Filename Value="demo1"/>
+ </Target>
+ <SearchPaths>
+ <IncludeFiles Value="$(ProjOutDir)"/>
+ <OtherUnitFiles Value="../src"/>
+ <UnitOutputDirectory Value="lib/$(TargetCPU)-$(TargetOS)"/>
+ </SearchPaths>
+ </CompilerOptions>
+ <Debugging>
+ <Exceptions>
+ <Item>
+ <Name Value="EAbort"/>
+ </Item>
+ <Item>
+ <Name Value="ECodetoolError"/>
+ </Item>
+ <Item>
+ <Name Value="EFOpenError"/>
+ </Item>
+ </Exceptions>
+ </Debugging>
+</CONFIG>
diff --git a/packages/fcl-mustache/examples/demo1.lpr b/packages/fcl-mustache/examples/demo1.lpr
new file mode 100644
index 0000000000..652ec7057c
--- /dev/null
+++ b/packages/fcl-mustache/examples/demo1.lpr
@@ -0,0 +1,42 @@
+{ Demo for mustache engine with JSON context
+
+ Copyright (C) 2021 michael Van Canneyt michael@freepascal.org
+
+ This source is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
+
+ This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+ A copy of the GNU General Public License is available on the World Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can
+ also obtain it by writing to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.
+}
+program demo1;
+
+// jsonparser includes the json parser.
+
+uses jsonparser, fpmustache;
+
+Const
+ JSON = '{ "products" : [ {"name" : "BMW" }, {"name" : "Mercedes"}, { "name" : "Audi" }] }';
+
+ // Mock markdown table
+ Template =
+ '| name |'+sLineBreak+
+ '|------|'+sLineBreak+
+ '{{#products}}| {{name}} |'+sLineBreak+
+ '{{/products}}';
+
+Var
+ M : TMustache;
+
+begin
+ M:=TMustache.Create(Nil);
+ try
+ // Json support enabled by default
+ Writeln(M.Render(Template,JSON));
+ finally
+ M.Free;
+ end;
+end.
+
diff --git a/packages/fcl-mustache/examples/demo2.lpi b/packages/fcl-mustache/examples/demo2.lpi
new file mode 100644
index 0000000000..dd4e245773
--- /dev/null
+++ b/packages/fcl-mustache/examples/demo2.lpi
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<CONFIG>
+ <ProjectOptions>
+ <Version Value="12"/>
+ <General>
+ <Flags>
+ <MainUnitHasCreateFormStatements Value="False"/>
+ <MainUnitHasTitleStatement Value="False"/>
+ <MainUnitHasScaledStatement Value="False"/>
+ </Flags>
+ <SessionStorage Value="InProjectDir"/>
+ <Title Value="demo2"/>
+ <UseAppBundle Value="False"/>
+ <ResourceType Value="res"/>
+ </General>
+ <BuildModes>
+ <Item Name="Default" Default="True"/>
+ </BuildModes>
+ <PublishOptions>
+ <Version Value="2"/>
+ <UseFileFilters Value="True"/>
+ </PublishOptions>
+ <RunParams>
+ <FormatVersion Value="2"/>
+ </RunParams>
+ <Units>
+ <Unit>
+ <Filename Value="demo2.lpr"/>
+ <IsPartOfProject Value="True"/>
+ </Unit>
+ </Units>
+ </ProjectOptions>
+ <CompilerOptions>
+ <Version Value="11"/>
+ <Target>
+ <Filename Value="demo2"/>
+ </Target>
+ <SearchPaths>
+ <IncludeFiles Value="$(ProjOutDir)"/>
+ <OtherUnitFiles Value="../src"/>
+ <UnitOutputDirectory Value="lib/$(TargetCPU)-$(TargetOS)"/>
+ </SearchPaths>
+ </CompilerOptions>
+ <Debugging>
+ <Exceptions>
+ <Item>
+ <Name Value="EAbort"/>
+ </Item>
+ <Item>
+ <Name Value="ECodetoolError"/>
+ </Item>
+ <Item>
+ <Name Value="EFOpenError"/>
+ </Item>
+ </Exceptions>
+ </Debugging>
+</CONFIG>
diff --git a/packages/fcl-mustache/examples/demo2.lpr b/packages/fcl-mustache/examples/demo2.lpr
new file mode 100644
index 0000000000..4b5b20f885
--- /dev/null
+++ b/packages/fcl-mustache/examples/demo2.lpr
@@ -0,0 +1,48 @@
+{ Demo for mustache engine with database context
+
+ Copyright (C) 2021 michael Van Canneyt michael@freepascal.org
+
+ This source is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
+
+ This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+ A copy of the GNU General Public License is available on the World Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can
+ also obtain it by writing to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.
+}
+
+program demo2;
+
+uses csvdataset, fpmustache, fpdbmustache;
+
+Const
+ // Mock markdown table
+ Template =
+ '| name | age | '+sLineBreak+
+ '|------|------|'+sLineBreak+
+ '{{#family}}| {{name}} | {{age}} |'+sLineBreak+
+ '{{/family}}';
+
+Var
+ M : TMustache;
+ C : TMustacheDBContext;
+ D : TCSVDataset;
+
+begin
+ M:=TMustache.Create(Nil);
+ try
+ D:=TCSVDataset.Create(Nil);
+ D.CSVOptions.FirstLineAsFieldNames:=True;
+ D.LoadFromFile('family.csv');
+ C:=TMustacheDBContext.Create(Nil);
+ C.AddDataset(D,'family');
+ M.Template:=Template;
+ Writeln(M.Render(C));
+ finally
+ M.Free;
+ D.Free;
+ C.Free;
+ end;
+end.
+
diff --git a/packages/fcl-mustache/examples/family.csv b/packages/fcl-mustache/examples/family.csv
new file mode 100644
index 0000000000..628dc27a08
--- /dev/null
+++ b/packages/fcl-mustache/examples/family.csv
@@ -0,0 +1,7 @@
+name,age
+Father,30
+Mother,29
+Grandfather,62
+GrandMother,61
+Child 1,2
+Child 2,4
diff --git a/packages/fcl-mustache/examples/family.json b/packages/fcl-mustache/examples/family.json
new file mode 100644
index 0000000000..39475e98d1
--- /dev/null
+++ b/packages/fcl-mustache/examples/family.json
@@ -0,0 +1,10 @@
+{
+ "data" : [
+ { "name" : "Father", "age": 30 },
+ { "name" : "Mother", "age": 29 },
+ { "name" : "Grandfather", "age": 62 },
+ { "name" : "GrandMother", "age": 61 },
+ { "name" : "Child 1", "age": 2 },
+ { "name" : "Child 2", "age": 4 }
+ ]
+} \ No newline at end of file
diff --git a/packages/fcl-mustache/examples/family.tmpl b/packages/fcl-mustache/examples/family.tmpl
new file mode 100644
index 0000000000..b6174cfcfe
--- /dev/null
+++ b/packages/fcl-mustache/examples/family.tmpl
@@ -0,0 +1,22 @@
+<html>
+ <head>
+ <title>{{title}}</title>
+ </head>
+ <body>
+ <h1>Family members</h1>
+ <table>
+ <thead>
+ <tr>
+ <th>Name</th><th>Age</th>
+ </tr>
+ </thead>
+ <tbody>
+{{#data}}
+ <tr>
+ <td>{{name}}</td><td>{{age}}</td>
+ </tr>
+{{/data}}
+ </tbody>
+ </table>
+ </body>
+</html>
diff --git a/packages/fcl-mustache/examples/mustache.lpi b/packages/fcl-mustache/examples/mustache.lpi
new file mode 100644
index 0000000000..24c058f4a4
--- /dev/null
+++ b/packages/fcl-mustache/examples/mustache.lpi
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<CONFIG>
+ <ProjectOptions>
+ <Version Value="12"/>
+ <General>
+ <Flags>
+ <MainUnitHasCreateFormStatements Value="False"/>
+ <MainUnitHasTitleStatement Value="False"/>
+ <MainUnitHasScaledStatement Value="False"/>
+ </Flags>
+ <SessionStorage Value="InProjectDir"/>
+ <Title Value="Mustache Templater"/>
+ <UseAppBundle Value="False"/>
+ <ResourceType Value="res"/>
+ </General>
+ <BuildModes>
+ <Item Name="Default" Default="True"/>
+ </BuildModes>
+ <PublishOptions>
+ <Version Value="2"/>
+ <UseFileFilters Value="True"/>
+ </PublishOptions>
+ <RunParams>
+ <FormatVersion Value="2"/>
+ </RunParams>
+ <Units>
+ <Unit>
+ <Filename Value="mustache.lpr"/>
+ <IsPartOfProject Value="True"/>
+ </Unit>
+ </Units>
+ </ProjectOptions>
+ <CompilerOptions>
+ <Version Value="11"/>
+ <Target>
+ <Filename Value="mustache"/>
+ </Target>
+ <SearchPaths>
+ <IncludeFiles Value="$(ProjOutDir)"/>
+ <OtherUnitFiles Value="../src"/>
+ <UnitOutputDirectory Value="lib/$(TargetCPU)-$(TargetOS)"/>
+ </SearchPaths>
+ </CompilerOptions>
+ <Debugging>
+ <Exceptions>
+ <Item>
+ <Name Value="EAbort"/>
+ </Item>
+ <Item>
+ <Name Value="ECodetoolError"/>
+ </Item>
+ <Item>
+ <Name Value="EFOpenError"/>
+ </Item>
+ </Exceptions>
+ </Debugging>
+</CONFIG>
diff --git a/packages/fcl-mustache/examples/mustache.lpr b/packages/fcl-mustache/examples/mustache.lpr
new file mode 100644
index 0000000000..7a48df1dad
--- /dev/null
+++ b/packages/fcl-mustache/examples/mustache.lpr
@@ -0,0 +1,207 @@
+program mustache;
+
+{$mode objfpc}{$H+}
+
+uses
+ {$IFDEF UNIX}
+ cthreads,
+ {$ENDIF}
+ Classes, SysUtils, CustApp, strutils, fpjson, jsonparser, csvdataset, fpMustache, fpexmustache, fpdbmustache, iostream;
+
+type
+
+ { TMustacheApplication }
+
+ TMustacheApplication = class(TCustomApplication)
+ private
+ FTemplate : TMustacheString;
+ FJSON : TJSONStringType;
+ FCSV: TCSVDataset;
+ FPartials,
+ FDefines : TStrings;
+ FAllowExpressions : Boolean;
+ Foutput,
+ FSection,
+ FRootPath : String;
+ procedure DoGetDefine(const aName: TMustacheString; var aHandled: Boolean;
+ var aValue: TMustacheString);
+ procedure ProcessOptions;
+ Procedure Createoutput;
+ procedure Usage(ErrorMsg: String);
+ protected
+ procedure DoRun; override;
+
+ public
+ constructor Create(TheOwner: TComponent); override;
+ destructor Destroy; override;
+ end;
+
+{ TMustacheApplication }
+
+procedure TMustacheApplication.Usage(ErrorMsg : String);
+
+begin
+ If ErrorMsg<>'' then
+ Writeln('Error : ',ErrorMsg);
+ Writeln('Usage : mustache [options]');
+ Writeln('Where options is one or more of:');
+ writeln('-c --csv=FILE Use a CSV file as data source. First line must contain column names.');
+ writeln('-d --define=name=value Define fixed value.');
+ writeln('-e --expressions Allow expressions.');
+ writeln('-h --help This message.');
+ writeln('-j --json=JSON Use JSON as data source. @FILENAME will read JSON from file (UTF8).');
+ writeln('-o --output=FILE output file to write output to. If empty, stdout is assumed.');
+ writeln('-p --partial=name=PARTIAL Register partial. @FILENAME reads partial from file.');
+ writeln('-r --root=PATH Register variables at root path PATH for expression engine');
+ writeln('-s --section=SECTIOn Section name for CSV data');
+ writeln('-t --template=TEMPLATE Use TEMPLATE as data source. @FILENAME will read template from file (UTF8). Required.');
+ Halt(Ord(ErrorMsg<>''));
+end;
+
+procedure TMustacheApplication.ProcessOptions;
+
+ Function StringOrFile(S : String) : UTF8String;
+
+ begin
+ if Copy(S,1,1)<>'@' then
+ Result:=S
+ else
+ With TFileStream.Create(Copy(S,2,Length(S)-1),fmOpenRead or fmShareDenyNone) do
+ try
+ SetLength(Result,Size);
+ ReadBuffer(Result[1],Size);
+ finally
+ Free;
+ end;
+ end;
+
+Var
+ S : String;
+
+begin
+ if Not HasOption('t','template') then
+ Raise Exception.Create('Need a template');
+ if HasOption('c','csv') and HasOption('j','json') then
+ Raise Exception.Create('Cannot specify both JSON or CSV');
+ FTemplate:=StringOrFile(GetOptionValue('t','template'));
+ if HasOption('j','json') then
+ FJSON:=StringOrFile(GetOptionValue('j','json'))
+ else if HasOption('c','csv') then
+ begin
+ FCSV:=TCSVDataset.Create(Self);
+ FCSV.FileName:=GetOptionValue('c','csv');
+ FCSV.CSVOptions.FirstLineAsFieldNames:=True;
+ FCSV.Open;
+ end;
+ for S in GetOptionValues('d','define') do
+ FDefines.Add(S);
+ for S in GetOptionValues('p','partial') do
+ FPartials.Add(ExtractWord(1,S,['='])+'='+StringOrFile(ExtractWord(2,S,['='])));
+ FAllowExpressions:=HasOption('e','expressions');
+ FRootPath:=GetOptionValue('r','root');
+ FSection:=GetOptionValue('s','section');
+ if FSection='' then
+ FSection:='data';
+ Foutput:=GetOptionValue('o','output');
+end;
+
+procedure TMustacheApplication.DoGetDefine(const aName: TMustacheString;
+ var aHandled: Boolean; var aValue: TMustacheString);
+
+Var
+ Idx : Integer;
+
+begin
+ Writeln('Getting define ',aName);
+ Idx:=FDefines.IndexOfName(aName);
+ aHandled:=Idx<>-1;
+ if aHandled then
+ aValue:=FDefines.ValueFromIndex[Idx]
+ else
+ aValue:='';
+end;
+
+procedure TMustacheApplication.DoRun;
+var
+ ErrorMsg: String;
+begin
+ Terminate;
+ // quick check parameters
+ ErrorMsg:=CheckOptions('het:j:c:d:o:r:', ['help','template','json','csv','define','output','expressions','root']);
+ if (ErrorMsg<>'') or HasOption('h','help') then
+ Usage(ErrorMsg);
+ ProcessOptions;
+ CreateOutput;
+end;
+
+procedure TMustacheApplication.CreateOutput;
+
+Var
+ M : TMustache;
+ C : TMustacheContext;
+ O : TStream;
+ S : TMustacheString;
+
+begin
+ O:=Nil;
+ M:=Nil;
+ C:=Nil;
+ try
+ if FAllowExpressions then
+ M:=TMustache.Create(Self)
+ else
+ begin
+ M:=TMustacheExpr.Create(Self);
+ if (FRootPath<>'') and (FJSON<>'') then
+ TMustacheExpr(M).RegisterVariables(FJSON,FRootPath,True);
+ end;
+ M.Partials:=FPartials;
+ if Assigned(FCSV) then
+ begin
+ C:=TMustacheDBContext.Create(@DoGetDefine);
+ TMustacheDBContext(C).AddDataset(FCSV,FSection);
+ end
+ else if (FJSON<>'') then
+ C:=TMustacheJSONContext.Create(GetJSON(FJSON),@DoGetDefine)
+ else
+ C:=TMustacheContext.Create(@DoGetDefine);
+ if Foutput<>'' then
+ O:=TFileStream.Create(Foutput,fmCreate)
+ else
+ O:=TIOStream.Create(iosOutput);
+ M.Template:=FTemplate;
+ S:=M.Render(C);
+ O.WriteBuffer(S[1],Length(S));
+ finally
+ O.Free;
+ C.Free;
+ M.Free;
+ end;
+end;
+
+constructor TMustacheApplication.Create(TheOwner: TComponent);
+begin
+ inherited Create(TheOwner);
+ FPartials:=TStringList.Create;
+ FDefines:=TStringList.Create;
+ StopOnException:=True;
+end;
+
+destructor TMustacheApplication.Destroy;
+begin
+ FreeAndNil(FPartials);
+ FreeAndNil(FDefines);
+ FreeAndNil(FCSV);
+ inherited Destroy;
+end;
+
+
+var
+ Application: TMustacheApplication;
+begin
+ Application:=TMustacheApplication.Create(nil);
+ Application.Title:='Mustache Templater';
+ Application.Run;
+ Application.Free;
+end.
+