我有一个基本的.NET字典(字典)。在我的ToLiquid方法中,我确实序列化/公开了Dictionary对象。我的问题是,我如何才能像在常规.NET中那样遍历液态模板中的键?似乎您必须知道实际的键才能访问liquid模板中的值。
我知道您可以像这样访问liquid模板中的值
item.dictionary"myKey“
然而,我不知道实际的键,所以我更喜欢使用DotLiquid中的"for“结构来迭代键,以便获得各种值。由于"for“构造在集合上工作,而Dictionary是一个集合,我认为这可以以某种方式完成,但我尝试的所有排列都失败了。
任何帮助都将不胜感激。
发布于 2012-03-02 11:42:36
如果您只需要访问字典中的值,则可以这样做:
[Test]
public void TestForWithDictionary()
{
var dictionary = new Dictionary<string, string>
{
{ "Graham Greene", "English" },
{ "F. Scott Fitzgerald", "American" }
};
Helper.AssertTemplateResult(" English American ", "{% for item in authors %} {{ item }} {% endfor %}",
Hash.FromAnonymousObject(new { authors = dictionary.Values }));
}但是,如果您确实需要访问for循环中的键和值,那么当前版本的DotLiquid (1.6.1)不支持这一点。
发布于 2013-04-23 12:21:46
只需为字典对象创建一个drop。然后使用它来包装您的成员,这些成员是您的drops中的字典。即:
public class MyDictionaryDrop : Drop
{
private Dictionary<string,string> _myDictionary;
public DictionaryDrop<string, string> MyDictionary
{
get
{
return new DictionaryDrop<string, string>(_myDictionary);
}
}
}
public class DictionaryDrop<TKey,TValue> : Drop ,IEnumerable
{
private readonly Dictionary<TKey, TValue> _dictionary;
public DictionaryDrop(Dictionary<TKey,TValue> dictionary)
{
_dictionary = dictionary;
}
public ICollection<TKey> Keys { get { return _dictionary.Keys; } }
public ICollection<TValue> Values { get { return _dictionary.Values; } }
public TValue this[TKey key] { get { return _dictionary[key]; } }
public IEnumerator GetEnumerator()
{
return _dictionary.GetEnumerator();
}
}https://stackoverflow.com/questions/9503525
复制相似问题