Template.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text.RegularExpressions;
  4. namespace Masuit.Tools.Strings
  5. {
  6. /// <summary>
  7. /// 模版引擎
  8. /// </summary>
  9. public class Template
  10. {
  11. private string Content { get; set; }
  12. /// <summary>
  13. /// 模版引擎
  14. /// </summary>
  15. /// <param name="content"></param>
  16. public Template(string content)
  17. {
  18. Content = content;
  19. }
  20. /// <summary>
  21. /// 创建模板
  22. /// </summary>
  23. /// <param name="content"></param>
  24. /// <returns></returns>
  25. public static Template Create(string content)
  26. {
  27. return new Template(content);
  28. }
  29. /// <summary>
  30. /// 设置变量
  31. /// </summary>
  32. /// <param name="key"></param>
  33. /// <param name="value"></param>
  34. /// <returns></returns>
  35. public Template Set(string key, string value)
  36. {
  37. Content = Content.Replace("{{" + key + "}}", value);
  38. return this;
  39. }
  40. /// <summary>
  41. /// 设置变量
  42. /// </summary>
  43. public Template Set(object obj)
  44. {
  45. var dic = obj.ToDictionary();
  46. Set(dic);
  47. return this;
  48. }
  49. /// <summary>
  50. /// 设置变量
  51. /// </summary>
  52. public Template Set(Dictionary<string, string> dic)
  53. {
  54. foreach (var x in dic)
  55. {
  56. Content = Content.Replace("{{" + x.Key + "}}", x.Value);
  57. }
  58. return this;
  59. }
  60. /// <summary>
  61. /// 渲染模板
  62. /// </summary>
  63. /// <param name="check">是否检查未使用的模板变量</param>
  64. /// <returns></returns>
  65. public string Render(bool check = false)
  66. {
  67. if (check)
  68. {
  69. var mc = Regex.Matches(Content, @"\{\{.+?\}\}");
  70. foreach (Match m in mc)
  71. {
  72. throw new ArgumentException($"模版变量{m.Value}未被使用");
  73. }
  74. }
  75. return Content;
  76. }
  77. }
  78. }