3

Let's assume I have the following template:

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

The user is allowed to enter both the template and the placeholders/variables, so I have no way of telling what will the placeholders be like.

I was thinking of creating something like this:

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

There is a method called FromDictionary that accepts a Dictionary and I don't really understand how it works. The other alternative is FromAnonymousObject, but I don't know how to convert the Dictionary to an anonymous object to fit the purpose.

Any ideas would be greatly appreciated!

4

1 回答 1

5

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

(我在没有编译的情况下输入了这个,所以如果有错误,请道歉。让我知道,我会更新答案。)

于 2015-01-12T10:27:30.790 回答