forked from lukencode/FluentEmail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RazorRenderer.cs
63 lines (55 loc) · 1.56 KB
/
RazorRenderer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using FluentEmail.Core.Interfaces;
using RazorLight;
using RazorLight.Razor;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace FluentEmail.Razor
{
public class RazorRenderer : ITemplateRenderer
{
private readonly RazorLightEngine _engine;
public RazorRenderer(string root = null)
{
_engine = new RazorLightEngineBuilder()
.UseFileSystemProject(root ?? Directory.GetCurrentDirectory())
.UseMemoryCachingProvider()
.Build();
}
public RazorRenderer(RazorLightProject project)
{
_engine = new RazorLightEngineBuilder()
.UseProject(project)
.UseMemoryCachingProvider()
.Build();
}
public RazorRenderer(Type embeddedResRootType)
{
_engine = new RazorLightEngineBuilder()
.UseEmbeddedResourcesProject(embeddedResRootType)
.UseMemoryCachingProvider()
.Build();
}
public Task<string> ParseAsync<T>(string template, T model, bool isHtml = true)
{
dynamic viewBag = (model as IViewBagModel)?.ViewBag;
return _engine.CompileRenderStringAsync<T>(GetHashString(template), template, model, viewBag);
}
string ITemplateRenderer.Parse<T>(string template, T model, bool isHtml)
{
return ParseAsync(template, model, isHtml).GetAwaiter().GetResult();
}
public static string GetHashString(string inputString)
{
var 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();
}
}
}