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!
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.)