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!

T.S.
  • 18,195
  • 11
  • 58
  • 78
user2642287
  • 129
  • 1
  • 2
  • 11

1 Answers1

5

Hash.FromDictionary is indeed the method you want. I think you were very close to the answer - you just need to convert your Dictionary<string, string> to Dictionary<string, object>. (The values are object because you can include nested objects in there, in addition to primitive types.)

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

(I've typed this into SO without compiling it, so apologies if there are mistakes. Let me know and I'll update the answer.)

Tim Jones
  • 1,766
  • 12
  • 17
  • thank you. The one thing I didn't understand from the beginning and kept doing wrong was that in the dictionary I was passing the key in the following format: "{{ keyName }}", instead of just "keyName". – user2642287 Jan 16 '15 at 08:56