2014-09-22 66 views
0

是否可以通過字符串引用訪問集合項目而不是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"] 

我可以通過name元素山坳訪問[「行」]的元素在DotLiquid模板?如果是的話,我該如何實現這一點?

回答

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

「行」將被原樣傳遞到MyCollectionDrop.BeforeMethodmethod參數。

請注意,您還需要使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]); 
}