5

I am using DotLiquid template engine and trying access dictionary value in template. I have passed to template this drop:

public class SomeDrop : Drop
{
   public Dictionary<string, object> MyDictionary {get; set;}
}

var someDropInstance = SomeDrop 
{
   MyDictionary = new Dictionary<string, object> {{"myKey", 1}}
}

Template.NamingConvention = new CSharpNamingConvention();

var preparedTemplate = Template.Parse(template);
var templateOutput = preparedTemplate.Render(Hash.FromAnonymousObject(new { @this = someDropInstance }));

In template i can't access to myKey value as {{ this.MyDictionary.myKey }} neither as {{ this.MyDictionary['myKey'] }}

4

2 回答 2

8

您需要Template.NamingConvention在创建任何放置对象之前进行设置。出于性能原因,基本Drop构造函数使用当前命名约定缓存所有公共实例成员。即使您随后更改了命名约定,这些缓存的属性也不会重置。

这段代码对我有用:

public class SomeDrop : Drop
{
    public Dictionary<string, object> MyDictionary { get; set; }
}

[Test]
public void StackOverflow()
{
    Template.NamingConvention = new CSharpNamingConvention();
    const string template = "{{ this.MyDictionary.myKey }}";

    var someDropInstance = new SomeDrop
    {
        MyDictionary = new Dictionary<string, object> { { "myKey", 1 } }
    };

    var preparedTemplate = Template.Parse(template);
    Assert.That(
        preparedTemplate.Render(Hash.FromAnonymousObject(new { @this = someDropInstance })),
        Is.EqualTo("1"));
}

我承认这有点棘手——这不是一次提出这个问题。我还没有想出一个令人满意的解决方案,但欢迎任何建议。

于 2011-11-16T17:54:21.147 回答
0

MyDictionary["myKey"]只需像或一样访问它MyDictionary.TryGetValue("myKey", out result)。没有多余的{{ }}

于 2011-11-16T15:22:10.820 回答