我正在使用 Scriban 为邮件服务呈现 html 模板。Scriban 允许我使用对象和 html 模板来呈现 html,如下所示:
<ul id='model'>\n<h2>Name 2: {{ model.Username }}</h2>\n<h1>Message 2: {{ model.Password }}</h1>\n</ul>
我需要验证动态对象中是否存在某些属性。在上面的例子中,匹配的动态对象需要包含一个“用户名”属性和一个“密码”属性。
我创建了一个可行的解决方案,但它非常hacky,让我羞于称自己为开发人员,并且绝不会成为我最终解决方案的一部分:
private readonly string template = "<ul id='model'>\n<h2>Name 2: {{ model.Username }}</h2>\n<h1>Message 2: {{ model.Password }}</h1>\n</ul>";
private readonly dynamic model = new {Username = "user1", Password = "pass"};
public void Validate()
{
//Convert dynamic object to dictionary
var data = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(model));
//Regex pattern for finding properties in html-string
Regex pattern = new Regex("(?<={{ )(.*?)(?= }})");
//Properties in html-string
MatchCollection matches = pattern.Matches(template);
//Check if dynamic object contains a property for each match
foreach (Match match in matches)
{
var matchString = match.ToString();
//Remove "model." from match. This should be done by regex instead.
var property = matchString.Substring(matchString.IndexOf('.') +1);
//Throws an exception, if the dynamic object doesnt contain the property.
var result = data[property];
}
}
如何验证动态对象中是否存在某个属性?