Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Text;
- namespace SkillSource.Infrastructure.Web
- {
- public static class TemplateReplacer
- {
- /// <summary>
- /// Replaces all [tags] and [tag.tags] found in the template with the corresponding value in the model
- /// </summary>
- /// <param name="template">the template</param>
- /// <param name="model">any model</param>
- /// <returns>the filled in template</returns>
- public static string Replace(string template, object model)
- {
- var result = new StringBuilder();
- for (var pos = 0;pos < template.Length;) {
- var nextOpenBracket = template.IndexOf('[', pos);
- if (nextOpenBracket >= 0) {
- result.Append(template.Substring(pos, nextOpenBracket - pos));
- var nextCloseBracket = template.IndexOf(']', nextOpenBracket);
- if (nextCloseBracket >= 0) {
- pos = nextCloseBracket + 1;
- var path = template.Substring(nextOpenBracket + 1, nextCloseBracket - nextOpenBracket - 1);
- result.Append(ResolvePath(model, path));
- }
- else throw new InvalidOperationException("Bracket at pos " + nextOpenBracket + " not closed!");
- }
- else {
- // till end of template
- result.Append(template.Substring(pos));
- break;
- }
- }
- return result.ToString();
- }
- private static string ResolvePath(object model, string paths)
- {
- var parts = paths.Split('.');
- object[] value = {model};
- foreach (var property in parts.Select(part => value[0].GetType().GetProperty(part))) {
- if (property == null) return "[" + paths + "]";
- value[0] = property.GetValue(value[0], null);
- }
- return value[0].ToString();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment