Skip to content

Instantly share code, notes, and snippets.

@vanillajonathan
Last active August 14, 2020 09:57
Show Gist options
  • Save vanillajonathan/8253c4a2ac350996fec0 to your computer and use it in GitHub Desktop.
Save vanillajonathan/8253c4a2ac350996fec0 to your computer and use it in GitHub Desktop.
A very basic general-purpose substitution-based template engine.
public void Main()
{
var template = "Hello {{Name}}, how are you?";
var model = new { Name = "Alice" };
var output = TemplateEngine.Execute(template, model);
// Output: "Hello Alice, how are you?"
}
public class TemplateEngine
{
/// <summary>
/// Parses the template and fuses it with the data model.
/// </summary>
/// <param name="template">The template which is acted upon.</param>
/// <param name="model">The model which is fed to the template.</param>
/// <exception cref="FormatException">Property not found in model.</exception>
/// <returns>A string generated from the template.</returns>
public static string Execute(string template, object model)
{
var modelType = model.GetType();
foreach (var match in Regex.Matches(template, @"{{\w+}}"))
{
var propertyName = match.ToString().Trim(new[] {'{', '}'});
var property = modelType.GetProperty(propertyName);
if (property == null)
{
throw new FormatException("Property '" + propertyName + "' does not exist in model.");
}
template = template.Replace(match.ToString(), property.GetValue(model, null).ToString());
}
return template;
}
/// <summary>
/// Parses the template and fuses it with the data model.
/// </summary>
/// <param name="template">The template which is acted upon.</param>
/// <param name="model">The model which is fed to the template.</param>
/// <exception cref="KeyNotFoundException">Property not found in model.</exception>
/// <returns>A string generated from the template.</returns>
public static string Execute(string template, IDictionary<string, string> model)
{
foreach (var match in Regex.Matches(template, @"{{\w+}}"))
{
var propertyName = match.ToString().Trim(new[] { '{', '}' });
template = template.Replace(match.ToString(), model[propertyName]);
}
return template;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment