【问题标题】:DotLiquid: Loop through a (Wrapped) Dictionary<string, string> in for-loop in templateDotLiquid:在模板中的 for 循环中循环遍历(包装的)Dictionary<string, string>
【发布时间】:2016-04-12 09:03:17
【问题描述】:

就我know 而言,DotLiquid(使用版本 1.8.0.0)不支持 C# Dictionary 开箱即用的构造。它们必须包装在 Drop-Object 中。

所以我尝试根据我的用例调整 Tim Jones 的答案。可悲的是,这没有按预期工作,所以我希望有人能告诉我我哪里出了问题,因为我没有想法。

这是包含字典的包装模型类(其中之一):

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

现在看来,我实际上在我的 Template.Parse 方法中 get 了正确的值。我只是没有让它们脱离我的结构,因为......?任何帮助表示赞赏。老实说,我认为我在这里基本上遗漏了一些东西。

【问题讨论】:

    标签: c# dictionary liquid dotliquid


    【解决方案1】:

    问题在于,您尝试访问的KeyValue 属性的KeyValuePair&lt;T&gt; 既不是Drop,也不是实现ILiquidizable

    如果您想像这样遍历字典中的项目,则必须创建一个 KeyValueDrop 包装器,并公开一个 List,而不是字典。

    【讨论】:

      猜你喜欢
      • 2012-06-16
      • 2015-03-20
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多