Skip to content

Instantly share code, notes, and snippets.

@rofr
Last active August 29, 2015 14:10
Show Gist options
  • Save rofr/ab9b6868f81c09b8aa79 to your computer and use it in GitHub Desktop.
Save rofr/ab9b6868f81c09b8aa79 to your computer and use it in GitHub Desktop.
public class Template
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
public readonly string Body;
private HashSet<string> _keys;
public const string KeyExpression = @"{(?<key>[^}]+)}";
public bool RenderEmptyStringForMissingKeys { get; set; }
public Template(string body)
{
Body = body;
_keys = new HashSet<string>();
//Collect all the keys from the template
Regex.Replace(Body, KeyExpression, k => {
_keys.Add(k.Groups["key"].Value);
return "";
});
}
private static Dictionary<string,object> _emptyDefaults = new Dictionary<string, object>();
public string Render(IDictionary<string,object> args, IDictionary<string,object> defaults = null)
{
defaults = defaults ?? _emptyDefaults;
//Validate(args);
return Regex.Replace(Body, KeyExpression, m => Replace(m, args, fallback));
}
private void Validate(IDictionary<string, object> args)
{
var message = String.Format("Rendering template with {0} keys and {1} args", _keys.Count, args.Count);
_logger.Trace(message);
foreach (string key in _keys.Except(args.Keys))
{
_logger.Warn("Unassigned key: " + key);
}
foreach (string key in args.Keys.Except(_keys))
{
_logger.Warn("Unused arg: " + key);
}
}
private string Replace(Match match, IDictionary<string,object> args, IDictionary<string,object> defaults)
{
string key = match.Groups["key"].Value;
if (!args.ContainsKey(key)) args = defaults;
if (args.ContainsKey(key))
{
string result = args[key].ToString();
return result;
}
else if (RenderEmptyStringForMissingKeys) return "";
else return "{" + key + "}";
}
public static Template Load(string path)
{
string body = File.ReadAllText(path);
return new Template(body);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment