DotLiquid/Liquid access to dictionary

家住魔仙堡 提交于 2019-12-05 01:06:00

问题


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'] }}


回答1:


You need to set Template.NamingConvention before creating any drop objects. For performance reasons, the base Drop constructor caches all public instance members using the current naming convention. Even if you then change the naming convention, those cached properties are not reset.

This code works for me:

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

I admit this is a bit of a gotcha - this is not the first time this issue has been raised. I haven't yet come up with a satisfactory solution, but any suggestions are welcome.




回答2:


Just access it like MyDictionary["myKey"] or MyDictionary.TryGetValue("myKey", out result). No extra {{ }}.



来源:https://stackoverflow.com/questions/8153929/dotliquid-liquid-access-to-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!