I am in the process of writing a TemplateEngine. The intention is that will read in a HTML file containing placeholders. Something along the lines of <p><Dear |*name|* you have won 1st prize in |*competition|* thanks for your entry on |*date|*</p>
where anything between || needs to be replaced by data from a key value pair dictionary.
I currently initialise a dictionary manually like this:
mergeData.Add("name", dataRow["UserName"].ToString());
mergeData.Add("competiton", dataRow["CompName"].ToString());
mergeData.Add("date", dataRow["EntryDate"].ToString());
templateEngine.Initialise(mergeData);
templateEngine.Run();`
As you can see it makes use of a few magic strings. What I would like to do is make it a bit more extensible so that the placeholders and replacements could be defined externally. At the moment I am explictly specifying which columns to use for the data in code. I think that maybe a DataTable would work for the Initialise() but not sure how to approach it. Any ideas / suggestions would be most welcome.
public class TemplateEngine
{
private string _template;
private bool _initialised = false;
private Dictionary<string, string> _mergeData;
private TemplateEngine(string templateString)
{
_template = templateString;
}
public void Initialise(Dictionary<string, string> mergeData)
{
if (mergeData == null)
{
_initialised = false;
throw new ArgumentException("Must specify key value pairs to perform merge correctly");
}
_mergeData = mergeData;
_initialised = true;
}
public string Run()
{
if (_initialised == false)
{
throw new Exception("Cannot run engine as mergeData dictionary is not initalised");
}
foreach (var kvp in _mergeData)
{
_template = _template.Replace("|*" + kvp.Key + "|*", kvp.Value);
}
return _template;
}
public static TemplateEngine FromFile(string filePath)
{
if (filePath == string.Empty)
{
throw new ArgumentException("FilePath not specified cannot instantiate TemplateEngine");
}
string html = System.IO.File.ReadAllText(filePath);
var templateEngine = new TemplateEngine(html);
return templateEngine;
}
}
}