问题
I have a basic .NET Dictionary (Dictionary). In my ToLiquid method I do indeed serialize/expose the Dictionary object. My question is how can I ITERATE over the keys in a liquid template just as you would do in regular .NET? It seems as though you MUST know the actual key in order to access the value in the liquid template.
I understand that you could access the value in the liquid template like such
item.dictionary["myKey"]
However I don't know the actual key, so I would prefer to use the "for" construct in DotLiquid to iterate over the keys in order to get the various values. Since the "for" construct works on collections and Dictionary is a collection I thought this could be done somehow but all permutations that I have tried have failed.
Any help would greatly be appreciated.
回答1:
If you only need access to the values in the dictionary, you can do this:
[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 }));
}
However, if you really do need to have access to both keys and values inside the for
loop, then this is not supported by the current version (1.6.1) of DotLiquid.
回答2:
Just create a drop for the dictionary object. Then use it to wrap your members that are dictionaries in your drops. IE:
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/dictionaries-and-dotliquid