Improved EmailTemplateService code organization
This commit is contained in:
parent
ea9c0a7384
commit
52edae5470
|
@ -67,20 +67,19 @@ public enum Constants {
|
||||||
FileSystem.GetEmailTemplate("newsletter", DefaultTemplates["newsletter"]);
|
FileSystem.GetEmailTemplate("newsletter", DefaultTemplates["newsletter"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public string Process(string templateName, Dictionary<Constants, object?> data) {
|
public string ApplyTokens(string template, Func<string, string?> replacer) {
|
||||||
var options = new MjmlOptions {
|
return TokenMatcher.Replace(template, t => replacer(t.Value[2..^2]) ?? "");
|
||||||
Beautify = false
|
}
|
||||||
};
|
|
||||||
|
public string GetTemplate(string templateName) {
|
||||||
|
return FileSystem.GetEmailTemplate(templateName,
|
||||||
|
DefaultTemplates.TryGetValue(templateName, out string? s) ? s : null)
|
||||||
|
?? throw new ApplicationException("Failed to retrieve mail template " + templateName + ".");
|
||||||
|
}
|
||||||
|
|
||||||
|
public string CompileTemplate(string template, string templateName = "unknown") {
|
||||||
|
var options = new MjmlOptions { Beautify = false };
|
||||||
|
|
||||||
string template = FileSystem.GetEmailTemplate(templateName,
|
|
||||||
DefaultTemplates.TryGetValue(templateName, out string? s) ? s : null)
|
|
||||||
?? throw new ApplicationException("Failed to retrieve mail template " + templateName + ".");
|
|
||||||
|
|
||||||
template = TokenMatcher.Replace(template, t =>
|
|
||||||
data.TryGetValue(Enum.Parse<Constants>(t.Value[2..^2], true), out object? v) ?
|
|
||||||
v?.ToString() ?? "" :
|
|
||||||
"");
|
|
||||||
|
|
||||||
(string html, var errors) = Renderer.Render(template, options);
|
(string html, var errors) = Renderer.Render(template, options);
|
||||||
|
|
||||||
foreach (var error in errors) {
|
foreach (var error in errors) {
|
||||||
|
@ -91,6 +90,12 @@ public enum Constants {
|
||||||
return html;
|
return html;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public string Process(string templateName, Dictionary<Constants, object?> data) {
|
||||||
|
string template = ApplyTokens(GetTemplate(templateName), token =>
|
||||||
|
data.TryGetValue(Enum.Parse<Constants>(token, true), out object? v) ? v?.ToString() : null);
|
||||||
|
return CompileTemplate(template, templateName);
|
||||||
|
}
|
||||||
|
|
||||||
[GeneratedRegex(@"(\[\[.*?\]\])",
|
[GeneratedRegex(@"(\[\[.*?\]\])",
|
||||||
RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.CultureInvariant)]
|
RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.CultureInvariant)]
|
||||||
private static partial Regex MyRegex();
|
private static partial Regex MyRegex();
|
||||||
|
|
Loading…
Reference in a new issue