Template.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.Text.RegularExpressions;
  3. namespace Masuit.Tools.Strings
  4. {
  5. /// <summary>
  6. /// 模版引擎
  7. /// </summary>
  8. public class Template
  9. {
  10. private string Content { get; set; }
  11. /// <summary>
  12. /// 模版引擎
  13. /// </summary>
  14. /// <param name="content"></param>
  15. public Template(string content)
  16. {
  17. Content = content;
  18. }
  19. /// <summary>
  20. /// 设置变量
  21. /// </summary>
  22. /// <param name="key"></param>
  23. /// <param name="value"></param>
  24. /// <returns></returns>
  25. public Template Set(string key, string value)
  26. {
  27. Content = Content.Replace("{{" + key + "}}", value);
  28. return this;
  29. }
  30. /// <summary>
  31. /// 渲染模板
  32. /// </summary>
  33. /// <returns></returns>
  34. public string Render()
  35. {
  36. var mc = Regex.Matches(Content, @"\{\{.+?\}\}");
  37. foreach (Match m in mc)
  38. {
  39. throw new ArgumentException($"模版变量{m.Value}未被使用");
  40. }
  41. return Content;
  42. }
  43. }
  44. }