You are not logged in.
Hello,
I have the following template:
{{Title}}
{{#Favorite}}
<strong><a href="{{Link}}">{{Name}}<a></strong><br />
{{/Favorite}}
and here is my (simplified) data classes:
type
TFavorite = class
public
property Name: String read fName write fName;
property Link: String read fLink write fName;
end;
TFavorites = class(TList<TFavorite>);
THTMLFile = class
public
property Title: String read fTitle write fTitle;
property Favorites: TFavorites read fFavorites;
end;
Here is my (simplified) function in set the data to the TSynMustache instance:
var
Mustache: TSynMustache;
HTMLFile: THTMLFile;
Doc: Variant;
begin
Mustache := TSynMustache.Parse(//template//);
TDocVariant.New(Doc);
TDocVariantData(Doc).AddValue('Title', HTMLFile.Title);
TDocVariantData(Doc).AddValue('Favorites', HTMLFile.Favorites); // <----- !!!
Result := Mustache.Render(Doc);
end;
I do not know how to set a list of data (HTMLFile.Favorites).
Many thanks for the help!!!
Offline
You may created nested TFavorite objects one by one into the doc TDocVariant.
A bit verbose, perhaps.
You may use our TSynPersistent + T*ObjArray feature.
type
TFavorite = class(TSynPersistent)
published
property Name: String read fName write fName;
property Link: String read fLink write fName;
end;
TFavoriteObjArray = array of TFavorite;
THTMLFile = class(TSynAutoCreateFields)
published
property Title: String read fTitle write fTitle;
property Favorites: TFavoriteObjArray read fFavorites;
end;
Take note that here we defined the serialized fields as PUBLISHED.
Then, THtmlFile would own the Favorites list, as a dynamic array of TFavorite instances.
No need to initialize/finalize then in THtmlFile.Create/Destroy: TSynAutoCreateFields parent class will do it for you.
You need to register once the TFavoriteObjArray:
TJSONSerializer.RegisterObjArrayForJSON(TypeInfo(TFavoriteObjArray),TFavorite);
You can then use ObjArrayAdd() to add some items to the dynamic array.
Then you serialize the instance into a TDocVariant, and apply it to Mustache:
Result := Mustache.Render(ObjectToVariant(HtmlFile));
Offline
Works, thanks!
Offline