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

时间:2014-09-22 23:48:28

标签: c# collections element dotliquid

是否可以通过字符串引用而不是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模板中的名称元素col [&#34; Rows&#34;]进行访问吗?如果是这样,我该如何实现呢?

1 个答案:

答案 0 :(得分:0)

是的,有可能。首先,定义一个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”将作为MyCollectionDrop.BeforeMethod参数原样传递给method

请注意,您还需要从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]);
}