Skip to content

Instantly share code, notes, and snippets.

@smchristensen
Created December 19, 2018 19:05
Show Gist options
  • Save smchristensen/bb776e715cae8261842be2a3e97c00c8 to your computer and use it in GitHub Desktop.
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
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();
}
}
}
@JasperE84
Copy link

JasperE84 commented Sep 27, 2020

Excellent! A lot more lightweight than adding all the razor deps to my MVC webapi :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment