DotLiquid - 字典<string,string>作为参数</string,string>

时间:2015-01-09 12:52:23

标签: c# .net dictionary template-engine dotliquid

我们假设我有以下模板:

Hi {{ name }}! Welcome back to {{ blog }}. Last log-in date: {{ date }}.

允许用户同时输入模板和占位符/变量,因此我无法确定占位符的含义。

我在想创造这样的东西:

public string Render(string text, Dictionary<string,string> placeholders)
{
    Template template = Template.Parse(text);
    return template.Render(Hash.FromSomething(placeholders));
}

有一个名为FromDictionary的方法接受一个字典,我真的不明白它是如何工作的。另一种选择是FromAnonymousObject,但我不知道如何将Dictionary转换为匿名对象以符合目的。

任何想法都将不胜感激!

1 个答案:

答案 0 :(得分:2)

Hash.FromDictionary确实是你想要的方法。我认为你非常接近答案 - 你只需要将Dictionary<string, string>转换为Dictionary<string, object>。 (值为object,因为除了基本类型之外,您还可以在其中包含嵌套对象。)

public string Render(string text, Dictionary<string,string> placeholders)
{
    Template template = Template.Parse(text);
    Dictionary<string, object> convertedPlaceholders =
        placeholders.ToDictionary(kvp => kvp.Key, kvp => (object) kvp.Value);
    return template.Render(Hash.FromDictionary(convertedPlaceholders));
}

(我已将其输入SO而不编译它,如果有错误,请道歉。让我知道,我会更新答案。)