DotLiquid-通过字符串索引器访问集合元素

本文关键字:访问 集合 元素 索引 字符串 DotLiquid- | 更新日期: 2023-09-27 18:23:55

是否可以通过字符串引用而不是DotLiquid的索引偏移量来访问集合项?

public class MyItem
{
    public string Name;
    public object Value;
    public MyItem(string Name, object Value)
    {
        this.Name = Name;
        this.Value = Value;
    }
}
  public class MyCollection : List<MyItem>
{
    public MyCollection()
    {
        this.Add(new MyItem("Rows", 10));
        this.Add(new MyItem("Cols", 20));
    }
    public MyItem this[string name]
    {
        get
        {
            return this.Find(m => m.Name == name);
        }
    }
}

因此,在正常的c#中,如果我创建MyCollection类的实例,我就可以访问像这样的元素

MyCollection col =new MyCollection();
col[1] or col["Rows"]

我可以通过DotLiquid模板中的name元素col["Rows"]访问吗?如果是,我该如何实现?

DotLiquid-通过字符串索引器访问集合元素

是的,这是可能的。首先,定义一个Drop类,如下所示:

public class MyCollectionDrop : Drop
{
  private readonly MyCollection _items;
  public MyCollectionDrop(MyCollection items)
  {
    _items = items;
  }
  public override object BeforeMethod(string method)
  {
    return _items[method];
  }
}

然后,在呈现模板的代码中,将其实例添加到上下文中:

template.Render(Hash.FromAnonymousObject(new { my_items = new MyCollectionDrop(myCollection) }));

最后,在你的模板中这样访问它:

{{ my_items.rows.name }}

"rows"将按原样作为method参数传递给MyCollectionDrop.BeforeMethod

请注意,您还需要使MyItem继承自Drop,以便能够访问其属性。或者像这样写一个MyItemDrop类:

public class MyItemDrop : Drop
{
  private readonly MyItem _item;
  public MyItemDrop(MyItem item)
  {
    _item = item;
  }
  public string Name
  {
    get { return _item.Name; }
  }
  public string Value
  {
    get { return _item.Value; }
  }
}

然后将MyCollectionDrop.BeforeMethod更改为:

public override object BeforeMethod(string method)
{
  return new MyItemDrop(_items[method]);
}