Template class is following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Xml.Linq;
using System.Linq;
public class Templates
{
private Hashtable templates;
public Templates(string templatesFilePath)
{
templates = new Hashtable();
System.IO.StreamReader confFile = new System.IO.StreamReader(templatesFilePath);
XDocument configuration =XDocument.Parse(confFile.ReadToEnd());
var tpls = from cs in configuration.Descendants("Template")
select cs;
foreach (var t in tpls)
{
templates.Add(t.Attribute("Name").Value,t.Value);
}
}
/// <summary>
/// REnder templates with
/// </summary>
/// <param name="templateName"></param>
/// <param name="values"></param>
/// <returns></returns>
public string Render(string templateName, params string[] values)
{
Hashtable hash = new Hashtable();
for (int i = 0; i <= Math.Floor((decimal)values.Length/2); i+=2)
{
hash.Add(values[i], values[i + 1]);
}
return Render(templateName, hash);
}
/// <summary>
/// Renders
/// </summary>
/// <param name="templateName"></param>
/// <param name="values"></param>
/// <returns></returns>
public string Render(string templateName,Hashtable values)
{
string result = String.Empty;
if (templates.ContainsKey(templateName))
{
string template = (string)templates[templateName];
foreach (DictionaryEntry entry in values)
{
template = template.Replace("{$" + entry.Key + "}", "" + entry.Value);
}
result = template;
} else {
}
return result;
}
}
Sample template file will be looking like this:
<Templates>
<Template Name="template1">
<![CDATA[
My first template with {$Value1}
and {$Value2}
]]>
</Template>
<Template Name="template2">
<![CDATA[
My second template with {$Value3} and {$Value4}
]]>
</Template>
</Templates>
And code for calling this awesome template engine will be following:
Templates templates = new Templates(ConfigManager.AssemblyDirectory + @"\MyTemplates.xml");
var result=templates.Render("template1", "Value1", Aome Value1, "Value2", DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss")));
No comments:
Post a Comment