Template.cs 2.1 KB

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