【问题标题】:Is there a way to index through objects dnyamically in Scriban with C#?有没有办法在 Scriban 中使用 C# 动态索引对象?
【发布时间】:2020-06-30 14:49:18
【问题描述】:

使用 PDF 生成器,它使用模板引擎 Scriban 和 LaTeX。尽管我似乎无法引用 Scriban 试图通过索引表示法读取的 C# 对象(使用该数组索引处的数据)。我的意思是这样的:

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

我得到:Object document.template_data.tables[index] is null 这最终意味着无论出于何种原因编译器都无法检索该对象。


问:数据实际上在对象中吗? 答:是的,我硬编码了 0 和 1 之类的数字并获得了相关数据。我试图访问的两个字段就是这种情况。问题是尝试动态生成表格。

问:数组有大小吗? A:我已经在 scriban 中循环播放,只是大小吐出。有 5 张桌子。

问:你做过研究吗? A: 是的,这里有人在 github 上告诉人们这个问题已经解决了

Does Scriban support .NET Object Indexers?

Accessing object property using indexer notation

【问题讨论】:

    标签: c# xetex scriban


    【解决方案1】:

    您的问题实际上与索引超出范围有关。您正在循环 0 - 表格的大小。换句话说,该对象为空,因为您试图访问最后一个条目。我创建了一些超级简单的 POCO 来填充类似于您的代码的对象。

    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; }
    }
    

    这是循环遍历表格的更新脚本

    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);     
    

    结果如下:

    0: This works!!
    1: Row 2
    2: Row 3
    3: Row 4
    4: Row 5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      相关资源
      最近更新 更多