【问题标题】:DotLiquid/Liquid access to dictionaryDotLiquid/Liquid 访问字典
【发布时间】:2011-11-16 15:14:43
【问题描述】:

我正在使用DotLiquid 模板引擎并尝试访问模板中的字典值。 我已将此 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 }));

在模板中我无法访问 myKey 值 {{ this.MyDictionary.myKey }} 既不作为 {{ this.MyDictionary['myKey'] }}

【问题讨论】:

    标签: c# liquid dotliquid


    【解决方案1】:

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

    此代码适用于我:

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

    我承认这有点棘手 - 这不是 first 提出此问题的时间。我还没有想出令人满意的解决方案,但欢迎提出任何建议。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 模板中没有额外的{{ }}。完整的模板看起来像{{this.MyDictionary["myKey"]}}。仍然没有快乐。
      • 好的。字典不应该像MyDictionary = new Dictionary&lt;string, object&gt; { { "myKey", 1 } }; 那样实例化。您将其声明为 dict 但分配一个数组。
      • 是否可以看到 DotLiquid 从这些模板生成的代码?
      • 不,DotLiquid 不生成代码;这是一个字符串模板系统。
      猜你喜欢
      • 1970-01-01
      • 2012-08-10
      • 2020-01-16
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      相关资源
      最近更新 更多