0

Working on a PDF generator and it uses the Templating Engine Scriban and LaTeX. Although I cannot seem to reference the C# object Scriban is trying to read via index notation (use the data at this index of the array). I mean something like this:

{~for index in 0..document.template_data.tables.size~}} 
  {{ document.template_data.tables[index].data_matrix }}
{{ end }}

I get: Object document.template_data.tables[index] is null which ultimately means for whatever reason the compiler cannot retrieve that object.


Q: Is the data actually in the objects? A: Yes, I hardcoded in numbers like 0 and 1 and got relevant data. This was the case for two of the fields I was trying to access. The issue is trying to dynamically generate the tables.

Q: Does the array have a size? A: I've looped through in scriban with just the size spitting out. There are 5 tables.

Q: Did you do research? A: Yes, here are some people on github telling people the issue has been fixed

Does Scriban support .NET Object Indexers?

Accessing object property using indexer notation

tblev
  • 422
  • 4
  • 13

1 Answers1

1

Your issue is actually to do with the index out of bounds. You are looping through 0 - the size of the table. In other words, the object is null because you are trying to access past the last entry. I created some super simple POCOs to fill out the objects similar to your code.

public class Document
{
    public Data TemplateData { get; set; }
}
public class Data
{
    public List<TableRow> Tables { get; set; }
}
public class TableRow
{
    public string DataMatrix { get; set; }
}

Here is the updated script to loop through the tables

var bodyTextSub = @"{{~for index in 1..document.template_data.tables.size ~}} 
{{index - 1}}: {{ document.template_data.tables[index-1].data_matrix }}
{{ end }}";
var doc = new Document
{
    TemplateData = new Data
    {
        Tables = new List<TableRow>
        {
            new TableRow {DataMatrix = "This works!!"},
            new TableRow {DataMatrix = "Row 2"},
            new TableRow {DataMatrix = "Row 3"},
            new TableRow {DataMatrix = "Row 4"},
            new TableRow {DataMatrix = "Row 5"}
        }
    }
};
var template2 = Template.Parse(bodyTextSub);
var result2 = template2.Render(new {document = doc});
Console.WriteLine(result2);     

Here is the result:

0: This works!!
1: Row 2
2: Row 3
3: Row 4
4: Row 5
Bryan Euton
  • 919
  • 5
  • 12