using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Masuit.Tools.Strings; /// /// 模版引擎 /// public class Template { private string Content { get; set; } /// /// 模版引擎 /// /// public Template(string content) { Content = content; } /// /// 创建模板 /// /// /// public static Template Create(string content) { return new Template(content); } /// /// 设置变量 /// /// /// /// public Template Set(string key, string value) { Content = Content.Replace("{{" + key + "}}", value); return this; } /// /// 设置变量 /// public Template Set(object obj) { var dic = obj.ToDictionary(); Set(dic); return this; } /// /// 设置变量 /// public Template Set(Dictionary dic) { foreach (var x in dic) { Content = Content.Replace("{{" + x.Key + "}}", x.Value); } return this; } /// /// 设置变量 /// public Template Set(Dictionary dic) { foreach (var x in dic) { Content = Content.Replace("{{" + x.Key + "}}", x.Value.ToString()); } return this; } /// /// 渲染模板 /// /// 是否检查未使用的模板变量 /// public string Render(bool check = false) { if (check) { var mc = Regex.Matches(Content, @"\{\{.+?\}\}"); foreach (Match m in mc) { throw new ArgumentException($"模版变量{m.Value}未被使用"); } } return Content; } }