Created
December 19, 2018 19:05
-
-
Save smchristensen/bb776e715cae8261842be2a3e97c00c8 to your computer and use it in GitHub Desktop.
Handlebars.Net ITemplateRenderer for FluentEmail. Works best as a singleton as it will compile and store each template passed in
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Security.Cryptography; | |
using System.Text; | |
using System.Threading.Tasks; | |
using FluentEmail.Core.Interfaces; | |
using HandlebarsDotNet; | |
namespace FluentEmail.Renderers | |
{ | |
public class HandlebarsRenderer : ITemplateRenderer | |
{ | |
private readonly IHandlebars _handlebars; | |
private readonly Dictionary<string, Func<object, string>> _compiledTemplates = new Dictionary<string, Func<object, string>>(); | |
public HandlebarsRenderer(IHandlebars handlebars) { | |
_handlebars = handlebars; | |
} | |
public string Parse<T>(string template, T model, bool isHtml = true) { | |
return ParseAsync(template, model, isHtml).GetAwaiter().GetResult(); | |
} | |
public Task<string> ParseAsync<T>(string template, T model, bool isHtml = true) { | |
string templateHash = GetHashString(template); | |
Func<object, string> compiledTemplate = null; | |
if (!_compiledTemplates.ContainsKey(templateHash)) { | |
_compiledTemplates.Add(templateHash, _handlebars.Compile(template)); | |
} | |
compiledTemplate = _compiledTemplates[templateHash]; | |
return Task.Factory.StartNew(() => compiledTemplate(model)); | |
} | |
private static string GetHashString(string inputString) | |
{ | |
StringBuilder sb = new StringBuilder(); | |
var hashbytes = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(inputString)); | |
foreach (byte b in hashbytes) | |
{ | |
sb.Append(b.ToString("X2")); | |
} | |
return sb.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Excellent! A lot more lightweight than adding all the razor deps to my MVC webapi :)