2016-04-12 199 views
0

至于I know,DotLiquid(使用版本1.8.0.0)不支持C#Dictionary开箱即用的结构。它们必须包装在Drop-Object中。DotLiquid:循环遍历模板中的(包装)字典<字符串,字符串> for for循环

所以我试图改编蒂姆琼斯的答案,以供我使用。可悲的是,这并没有如预期的那样工作,所以我希望有人能够告诉我我在哪里出错,因为我不在意念之中。

这是(一)含有字典我的包裹模型类:

public class LegendAdditive : Drop 
{ 
    public LegendAdditive() 
    { 
     AdditiveDict = new Dictionary<string, string>(); 
    } 

    public Dictionary<string, string> AdditiveDict { get; set; } 
} 

类本身嵌入在LegendModel包含一些其他值:

public class LegendModel: Drop 
{ 
    ... 
    public LegendAdditive Additives { get; set; } 
    ... 
} 

正如你所看到的,所有的类都被包装成一个Drop,据我所知是使用字典(实现ILiquidizable等)的先决条件。

在一个转换器,这种模式是充满这样的:

public DotLiquid.Drop GetModel(MyObject plan) 
{ 
    ... 
    var LegendAdditives = new LegendAdditive(); 

    //dbLegend.Additives is a Dictionary<string, string> itself. 
    if (dbLegend.Additives.Any()) 
     foreach (var additive in dbLegend.Additives.OrderBy(a => a.Key)) 
      LegendAdditives.AdditiveDict.Add(additive.Key, additive.Value); 

    ... 

    LegendModel model = new LegendModel 
    { 
     ... 
     Additives = LegendAdditives, 
     ... 
    }; 

    return model; 
} 

和类ConvertToPdf,我有这样一个ConvertTemplate方法,解析模板:

public static string ConvertTemplate(ITemplateFileFactory templateFilePathFactory IDropModelConverter modelConverter, MyObject mplan) 
{ 
    //reading my filepath out of the factory here... 

    DotLiquid.Template.NamingConvention = new DotLiquid.NamingConventions.CSharpNamingConvention(); 

    Template templateObj = Template.Parse(template); // Parses and compiles the template 
    Drop plan = modelConverter.GetModel(mplan); 
    Hash hashedValues = Hash.FromAnonymousObject(new { plan }); 
    string ret = templateObj.Render(hashedValues); 
    return ret; 
} 

最后我的模板文件,我试图得到这个词典的值是这样的:

<div> 
    <dl> 
     {% for add in plan.Additives.AdditiveDict %} 
     <dt>{{add.Key}}</dt> 
     <dd>{{add.Value}}</dd> 
     {% endfor %} 
    </dl> 
</div> 

现在,该文件被正确解析,但是当我尝试访问我的循环的Dictionaryvalues我得到的,现在是这样的输出:

Liquid syntax error: Object '[18, Stärke]' is 
invalid because it is neither a built-in type 
nor implements ILiquidizable 

现在看来,其实我在我的模板得到正确的价值观.Parse方法。我只是没有让他们脱离我的结构,因为......?任何帮助表示赞赏。说实话,我觉得我在这里基本上失去了一些东西。

回答

1

的问题是,KeyValuePair<T>,您尝试访问的KeyValue性质,既不是Drop又不履行ILiquidizable

如果要循环查看字典中的项目,则必须创建一个KeyValueDrop包装,并公开List而不是字典。