diff --git a/Wave/Services/EmailTemplateService.cs b/Wave/Services/EmailTemplateService.cs index 8ebed30..1f05b53 100644 --- a/Wave/Services/EmailTemplateService.cs +++ b/Wave/Services/EmailTemplateService.cs @@ -67,20 +67,19 @@ public enum Constants { FileSystem.GetEmailTemplate("newsletter", DefaultTemplates["newsletter"]); } - public string Process(string templateName, Dictionary data) { - var options = new MjmlOptions { - Beautify = false - }; + public string ApplyTokens(string template, Func replacer) { + return TokenMatcher.Replace(template, t => replacer(t.Value[2..^2]) ?? ""); + } + + 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(t.Value[2..^2], true), out object? v) ? - v?.ToString() ?? "" : - ""); - (string html, var errors) = Renderer.Render(template, options); foreach (var error in errors) { @@ -91,6 +90,12 @@ public enum Constants { return html; } + public string Process(string templateName, Dictionary data) { + string template = ApplyTokens(GetTemplate(templateName), token => + data.TryGetValue(Enum.Parse(token, true), out object? v) ? v?.ToString() : null); + return CompileTemplate(template, templateName); + } + [GeneratedRegex(@"(\[\[.*?\]\])", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.CultureInvariant)] private static partial Regex MyRegex();