Template.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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="content"></param>
  23. /// <returns></returns>
  24. public static Template Create(string content)
  25. {
  26. return new Template(content);
  27. }
  28. /// <summary>
  29. /// 设置变量
  30. /// </summary>
  31. /// <param name="key"></param>
  32. /// <param name="value"></param>
  33. /// <returns></returns>
  34. public Template Set(string key, string value)
  35. {
  36. Content = Content.Replace("{{" + key + "}}", value);
  37. return this;
  38. }
  39. /// <summary>
  40. /// 渲染模板
  41. /// </summary>
  42. /// <param name="check">是否检查未使用的模板变量</param>
  43. /// <returns></returns>
  44. public string Render(bool check = false)
  45. {
  46. if (check)
  47. {
  48. var mc = Regex.Matches(Content, @"\{\{.+?\}\}");
  49. foreach (Match m in mc)
  50. {
  51. throw new ArgumentException($"模版变量{m.Value}未被使用");
  52. }
  53. }
  54. return Content;
  55. }
  56. }
  57. }