RazorLight Documentation

repository·master·Indexed 23 days ago

https://github.com/toddams/razorlight

A high-performance Razor template engine for .NET Standard 2.0 and .NET Core 3.0+ designed to work outside of ASP.NET MVC. It supports rendering templates from strings, files, embedded resources, and custom sources like databases. Features include memory caching, partial view support via IncludeAsync, and custom project implementations for template resolution.

Tokens
2.7K
Snippets
13
Records
14
Agent score
32%

What's inside RazorLight

  1. Use Includes (Partial Views)

    master

    Includes allow you to reuse template components. This feature requires the use of a RazorLight Project system (FileSystem, EmbeddedResources, or Custom) so the engine can locate the partial files.

    Syntax within a template: @{ await IncludeAsync("SomeView.cshtml", Model); }

    The first argument is the template key, and the second is the model to pass to the partial (which can be null).

    @model MyProject.TestViewModel
    <div
        Hello @Model.Title
    </div>
    
    @{ await IncludeAsync("SomeView.cshtml", Model); }
  2. How to test RazorLight in ASP.NET Core Integration Tests

    master

    RazorLight is not currently designed to support ASP.NET Core integration testing directly.

    Recommended Pattern:

    1. Create a dedicated project for your templating logic (e.g., <YourCompanyName>.<YourProjectName>.Templating).
    2. Implement your template rendering layer as a Domain Service within that project.
    3. In your integration tests, mock the dependencies of that service rather than attempting to run RazorLight directly.
  3. Quickstart: Render a template from a string

    master

    The simplest way to use RazorLight is to render a template directly from a string. Each template requires a unique templateKey so the engine can cache the compiled version and avoid redundant recompilation.

    Note: When using UseMemoryCachingProvider, you must also specify a project type (e.g., UseEmbeddedResourcesProject) even if you are only using strings, as the project system is required for partial view resolution.

    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);
  4. Resolve templates from Embedded Resources

    master

    To use templates embedded in your assembly, use UseEmbeddedResourcesProject.

    By default, the templateKey must be the full namespace of the project combined with the file name (e.g., ProjectName.Folder.FileName).

    You can simplify this by providing a root namespace to the builder, allowing you to use only the relative path/file name as the key.

    // Using full namespace
    var engine = new RazorLightEngineBuilder()
    	.UseEmbeddedResourcesProject(typeof(SomeService).Assembly)
    	.UseMemoryCachingProvider()
    	.Build();
    
    string html = await engine.CompileRenderAsync("EmailTemplates.Body", model);
    
    // Using root namespace to simplify keys
    var engineWithRoot = new RazorLightEngineBuilder()
    	.UseEmbeddedResourcesProject(typeof(SomeService).Assembly, "Project.Core.EmailTemplates")
    	.UseMemoryCachingProvider()
    	.Build();
    
    string htmlSimplified = await engineWithRoot.CompileRenderAsync("Body", model);
  5. Resolve templates from a Custom Source (e.g. Database)

    master

    If your templates are stored in a database or another external source, implement a custom RazorLightProject. This project class is responsible for providing the template source and ViewImports. RazorLight uses this project to resolve Layouts specified within templates.

    var project = new EntityFrameworkRazorProject(new AppDbContext());
    var engine = new RazorLightEngineBuilder()
                  .UseProject(project)
                  .UseMemoryCachingProvider()
                  .Build();
    
    // Using a GUID as a key
    string result = await engine.CompileRenderAsync("6cc277d5-253e-48e0-8a9a-8fe3cae17e5b", new { Name = "John Doe" });
    
    // Using an integer as a key
    int templateKey = 322;
    string resultInt = await engine.CompileRenderAsync(templateKey.ToString(), new { Name = "John Doe" });
  6. Handle HTML Encoding

    master

    By default, RazorLight encodes model values as HTML.

    To output a specific value without encoding, use the @Raw() function. To disable encoding for an entire document, set the DisableEncoding variable to true within a code block at the top of the template.

    /* Disable encoding for a specific value */
    string template = "Render @Raw(Model.Tag)";
    
    /* Disable encoding for the entire document */
    @model TestViewModel
    @{
        DisableEncoding = true;
    }
    
    <html
        Hello @Model.Tag
    </html
  7. Resolve templates from the File System

    master

    To use files from the local disk, use UseFileSystemProject with the root folder path. The templateKey provided to CompileRenderAsync should be the relative path from that root folder to the .cshtml file.

    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);
  8. Enable Intellisense support for RazorLight templates

    master

    To enable Visual Studio Intellisense for RazorLight templates, you must provide a hint to the IDE about the base template class. All templates implicitly inherit from TemplatePage<T>.

    @using RazorLight
    @inherits TemplatePage<MyModel>
    
    <html
        Your awesome template goes here, @Model.Name
    </html
  9. Workaround for Azure Functions dependency trimming issues

    master

    If you are using Azure Functions (specifically versions 3.0.4-3.0.5) and experiencing issues, you may need to disable 'Azure Functions dependency trimming'. Add the following to your root/entrypoint project's .csproj file:

    <PropertyGroup>
      <_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
    </PropertyGroup>
  10. Fix 'Cannot find reference assembly Microsoft.AspNetCore.Antiforgery.dll' on .NET Core 3.0+

    master

    On .NET Core 3.0 or higher, the SDK avoids copying references to the build output by default. If you encounter errors finding reference assemblies like Microsoft.AspNetCore.Antiforgery.dll, update your .csproj file to include these flags:

    <PropertyGroup>
        <PreserveCompilationReferences>true</PreserveCompilationReferences>
        <PreserveCompilationContext>true</PreserveCompilationContext>
    </PropertyGroup>
  11. Fix 'Cannot find compilation library' or 'Can't load metadata reference' errors

    master

    When deploying to a new machine or container, you may encounter errors regarding missing compilation libraries or metadata references. To resolve this, add the following properties to your entry point project's .csproj file:

    <PropertyGroup>
      <PreserveCompilationContext>true</PreserveCompilationContext>
      <MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish>
      <MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>
    </PropertyGroup>