1
1

Template.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text.RegularExpressions;
  4. namespace Masuit.Tools.Strings;
  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. public Template Set(object obj)
  43. {
  44. var dic = obj.ToDictionary();
  45. Set(dic);
  46. return this;
  47. }
  48. /// <summary>
  49. /// 设置变量
  50. /// </summary>
  51. public Template Set(Dictionary<string, string> dic)
  52. {
  53. foreach (var x in dic)
  54. {
  55. Content = Content.Replace("{{" + x.Key + "}}", x.Value);
  56. }
  57. return this;
  58. }
  59. /// <summary>
  60. /// 设置变量
  61. /// </summary>
  62. public Template Set(Dictionary<string, object> dic)
  63. {
  64. foreach (var x in dic)
  65. {
  66. Content = Content.Replace("{{" + x.Key + "}}", x.Value.ToString());
  67. }
  68. return this;
  69. }
  70. /// <summary>
  71. /// 渲染模板
  72. /// </summary>
  73. /// <param name="check">是否检查未使用的模板变量</param>
  74. /// <returns></returns>
  75. public string Render(bool check = false)
  76. {
  77. if (check)
  78. {
  79. var mc = Regex.Matches(Content, @"\{\{.+?\}\}");
  80. foreach (Match m in mc)
  81. {
  82. throw new ArgumentException($"模版变量{m.Value}未被使用");
  83. }
  84. }
  85. return Content;
  86. }
  87. }