RazorLight
Template engine based on Microsoft's Razor parsing engine for .NET Core
Install / Use
/learn @toddams/RazorLightREADME
RazorLight
Use Razor to build templates from Files / EmbeddedResources / Strings / Database or your custom source outside of ASP.NET MVC. No redundant dependencies and workarounds in pair with excellent performance and .NET Standard 2.0 and .NET Core 3.0 support.
Solidarity with Ukraine
Dear friends, my name is Ivan, I am the guy who created this library. I live in Ukraine, and if you are reading this message - I really hope you and your family are safe and healthy. 24 February Russia invaded my country with a series of missle atacks across entire Ukraine, from East to West. They started with destroying military infrastructure, and so-called "special operation", as they call it, in fact is a full scale war against us.
Update: it's been a long time since I first posted this message. Thank you for your enormous support, I am removing my volunteer donation account and instead providing you with the largest and proven charity organization in Ukraine - ComeBackAlive. If you have the possibility and desire to help Ukraine - that is the right place for your valuable donations. Thank you. Be safe
Table of contents
- Quickstart
- Template sources
- Includes (aka Partial)
- Encoding
- Additional metadata references
- Enable Intellisense support
- FAQ
Quickstart
Install the nuget package using following command:
Install-Package RazorLight -Version 2.3.0
The simplest scenario is to create a template from string. Each template must have a templateKey that is associated with it, so you can render the same template next time without recompilation.
<a id='snippet-simple'></a>
var engine = new RazorLightEngineBuilder()
// required to have a default RazorLightProject type,
// but not required to create a template from string.
.UseEmbeddedResourcesProject(typeof(ViewModel))
.SetOperatingAssembly(typeof(ViewModel).Assembly)
.UseMemoryCachingProvider()
.Build();
string template = "Hello, @Model.Name. Welcome to RazorLight repository";
ViewModel model = new ViewModel {Name = "John Doe"};
string result = await engine.CompileRenderStringAsync("templateKey", template, model);
<sup><a href='/tests/RazorLight.Tests/Snippets/Snippets.cs#L18-L32' title='Snippet source file'>snippet source</a> | <a href='#snippet-simple' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->To render a compiled template:
<!-- snippet: RenderCompiledTemplate --><a id='snippet-rendercompiledtemplate'></a>
var cacheResult = engine.Handler.Cache.RetrieveTemplate("templateKey");
if(cacheResult.Success)
{
var templatePage = cacheResult.Template.TemplatePageFactory();
string result = await engine.RenderTemplateAsync(templatePage, model);
}
<sup><a href='/tests/RazorLight.Tests/Snippets/Snippets.cs#L39-L46' title='Snippet source file'>snippet source</a> | <a href='#snippet-rendercompiledtemplate' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->Template sources
RazorLight can resolve templates from any source, but there are a built-in providers that resolve template source from filesystem and embedded resources.
File source
When resolving a template from filesystem, templateKey - is a relative path to the root folder, that you pass to RazorLightEngineBuilder.
<!-- snippet: FileSource --><a id='snippet-filesource'></a>
var engine = new RazorLightEngineBuilder()
.UseFileSystemProject("C:/RootFolder/With/YourTemplates")
.UseMemoryCachingProvider()
.Build();
var model = new {Name = "John Doe"};
string result = await engine.CompileRenderAsync("Subfolder/View.cshtml", model);
<sup><a href='/tests/RazorLight.Tests/Snippets/Snippets.cs#L51-L60' title='Snippet source file'>snippet source</a> | <a href='#snippet-filesource' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->EmbeddedResource source
For embedded resource, the key is the namespace of the project where the template exists combined with the template's file name.
The following examples are using this project structure:
Project/
Model.cs
Program.cs
Project.csproj
Project.Core/
EmailTemplates/
Body.cshtml
Project.Core.csproj
SomeService.cs
<!-- snippet: EmbeddedResourceSource -->
<a id='snippet-embeddedresourcesource'></a>
var engine = new RazorLightEngineBuilder()
.UseEmbeddedResourcesProject(typeof(SomeService).Assembly)
.UseMemoryCachingProvider()
.Build();
var model = new Model();
string html = await engine.CompileRenderAsync("EmailTemplates.Body", model);
<sup><a href='/tests/RazorLight.Tests/Snippets/Snippets.cs#L65-L74' title='Snippet source file'>snippet source</a> | <a href='#snippet-embeddedresourcesource' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->Setting the root namespace allows you to leave that piece off when providing the template name as the key:
<!-- snippet: EmbeddedResourceSourceWithRootNamespace --><a id='snippet-embeddedresourcesourcewithrootnamespace'></a>
var engine = new RazorLightEngineBuilder()
.UseEmbeddedResourcesProject(typeof(SomeService).Assembly, "Project.Core.EmailTemplates")
.UseMemoryCachingProvider()
.Build();
var model = new Model();
string html = await engine.CompileRenderAsync("Body", model);
<sup><a href='/tests/RazorLight.Tests/Snippets/Snippets.cs#L79-L88' title='Snippet source file'>snippet source</a> | <a href='#snippet-embeddedresourcesourcewithrootnamespace' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->Custom source
If you store your templates in database - it is recommended to create custom RazorLightProject that is responsible for gettings templates source from it. The class will be used to get template source and ViewImports. RazorLight will use it to resolve Layouts, when you specify it inside the template.
var project = new EntityFrameworkRazorProject(new AppDbContext());
var engine = new RazorLightEngineBuilder()
.UseProject(project)
.UseMemoryCachingProvider()
.Build();
// For key as a GUID
string result = await engine.CompileRenderAsync("6cc277d5-253e-48e0-8a9a-8fe3cae17e5b", new { Name = "John Doe" });
// Or integer
int templateKey = 322;
string result = await engine.CompileRenderAsync(templateKey.ToString(), new { Name = "John Doe" });
You can find a full sample here
Includes (aka Partial views)
Include feature is useful when you have reusable parts of your templates you want to share between different views. Includes are an effective way of breaking up large templates into smaller components. They can reduce duplication of template content and allow elements to be reused. This feature requires you to use the RazorLight Project system, otherwise there is no way to locate the partial.
@model MyProject.TestViewModel
<div>
Hello @Model.Title
</div>
@{ await IncludeAsync("SomeView.cshtml", Model); }
First argument takes a key of the template to resolve, second argument is a model of the view (can be null)
Encoding
By the default RazorLight encodes Model values as HTML, but sometimes you want to output them as is. You can disable encoding for specific value using @Raw() function
/* With encoding (default) */
string template = "Render @Model.Tag";
string result = await engine.CompileRenderAsync("templateKey", template, new { Tag = "<html>&" });
Console.WriteLine(result); // Output: <html>&
/* Without encoding */
string template = "Render @Raw(Model.Tag)";
string result = await engine.CompileRenderAsync("templateKey", template, new { Tag = "<html>&" });
Console.WriteLine(result); // Output: <html>&
In order to disable encoding for the entire document - just set "DisableEncoding" variable to true
@model TestViewModel
@{
DisableEncoding = true;
}
<html>
Hello @Model.Tag
</html>
Enable Intellisense support
Visual Studio tooling knows nothing about RazorLight and assumes, that the view you are using - is a typical ASP.NET MVC template. In order to enable Intellisense for RazorLight templates, you should give Visual Studio a little hint about the base template class, that all your templates inherit implicitly
@using RazorLight
@inherits TemplatePage<MyModel>
<html>
Your awesome template goes here, @Model.Name
</html>

FAQ
Coding Challenges (FAQ)
How to use templates from memory without setting a project?
The short answer is, you have to set a project to use the memory caching provider. The project doesn't have to do anything. This is by design, as without a project system, RazorLight cannot locate partial views.
:x: You used
