Skip to content

Switch from RazorEngine cshtml templates

Alexander edited this page Jul 1, 2020 · 7 revisions

Classic RazorEngine code

if (Engine.Razor.IsTemplateCached(TemplateName, typeof(BaseEmailModel)))
{
    parsedContent = Engine.Razor.Run(TemplateName, typeof(BaseEmailModel), model);
}
else
{
    var viewPath = Path.Combine(Statics.EmailTemplatesPath, $"{TemplateName}.cshtml");
    var viewContent = ReadTemplateContent(viewPath);
    parsedContent = Engine.Razor.RunCompile(viewContent, TemplateName, null, model);
}

RazorEngineCore code

private static ConcurrentDictionary<int, IRazorEngineCompiledTemplate> TemplateCache = new ConcurrentDictionary<int, IRazorEngineCompiledTemplate>();
int hashCode = TemplateName.GetHashCode();

IRazorEngineCompiledTemplate compiledTemplate = TemplateCache.GetOrAdd(hashCode, i =>
{
   RazorEngine razorEngine = new RazorEngine();
   string viewPath = Path.Combine(Statics.EmailTemplatesPath, TemplateName + ".cshtml");
   return razorEngine.Compile(File.ReadAllText(viewPath));
});

return compiledTemplate.Run(model); 

Template

You need to remove @model directive from template as the RazorEngineCore controls it. If you use strongly typed model and would like to keep IntelliSense suggestions, put @inherits directive ontop of template

@inherits RazorEngineCore.RazorEngineTemplateBase<MyModel>
...