2016-04-12 193 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而不是字典。