#1 2016-02-21 16:13:29

Weled1980
Member
Registered: 2016-02-21
Posts: 2

How to set a list of data to TSynMustache Template

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

#2 2016-02-21 16:31:19

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,242
Website

Re: How to set a list of data to TSynMustache Template

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

#3 2016-02-25 16:39:30

Weled1980
Member
Registered: 2016-02-21
Posts: 2

Re: How to set a list of data to TSynMustache Template

Works, thanks! smile

Offline

Board footer

Powered by FluxBB