字典和DotLiquid [英] Dictionaries and DotLiquid

查看:85
本文介绍了字典和DotLiquid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的.NET词典(字典).实际上,在我的ToLiquid方法中,我确实序列化/公开了Dictionary对象.我的问题是,如何像在常规.NET中一样对液体模板中的键进行迭代?似乎您必须知道实际的密钥,才能访问液体模板中的值.

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"]

item.dictionary["myKey"]

但是我不知道实际的键,所以我宁愿使用DotLiquid中的"for"构造对键进行迭代以获取各种值.因为"for"构造适用于集合,而Dictionary是一个集合,所以我认为可以以某种方式完成此操作,但是我尝试过的所有排列都失败了.

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.

任何帮助将不胜感激.

推荐答案

如果只需要访问字典中的值,则可以执行以下操作:

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

但是,如果确实需要访问for循环中的键和值,则当前版本的DotLiquid(1.6.1)不支持此操作.

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.

这篇关于字典和DotLiquid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆