Aspose.Word template foreach syntax

2.6k views Asked by At

I try build template in .doc file. I use mail merge to bind data.
In my template I use field like <<TableStart:ListData>> ... <<TableEnd:ListData>> to building table. I now how add if statement {IF ="True" ... }.
But how add foreach loop?
In this page: Mustache syntax is description of mustache syntax with foreach. How add this code to template.docx ?
My c# code - it may be usefull:

        var document = GetDocumentFromTemplate("SystemConfigurationTemplate.docx");
        var model = BuildModel();
        var asposeDataSource = new AsposeDataSource(document, model);
        document.MailMerge.Execute(asposeDataSource);
        document.Save(stream, SaveFormat.Pdf);
1

There are 1 answers

0
Awais Hafeez On

Please paste the following syntax in Word document:

{{ #foreach list }}{{ Number }}{{ /foreach list }}

You then need to call MailMerge.ExecuteWithRegions method to see foreach tag in action. Please see following code:

DataTable dataTable = new DataTable("list");
dataTable.Columns.Add("Number");

for (int i = 0; i < 10; i++)
{
    DataRow datarow = dataTable.NewRow();
    dataTable.Rows.Add(datarow);
    datarow[0] = "Number " + i.ToString();                
}

Document doc = new Document(MyDir + @"in.docx");

doc.MailMerge.UseNonMergeFields = true;
doc.MailMerge.ExecuteWithRegions(dataTable);

doc.Save(MyDir + @"17.8.docx");

I work with Aspose as Developer Evangelist.