RhoMicro.RazorTemplating 0.0.1-rc16

Prefix Reserved
This is a prerelease version of RhoMicro.RazorTemplating.
dotnet add package RhoMicro.RazorTemplating --version 0.0.1-rc16
                    
NuGet\Install-Package RhoMicro.RazorTemplating -Version 0.0.1-rc16
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="RhoMicro.RazorTemplating" Version="0.0.1-rc16" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RhoMicro.RazorTemplating" Version="0.0.1-rc16" />
                    
Directory.Packages.props
<PackageReference Include="RhoMicro.RazorTemplating" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add RhoMicro.RazorTemplating --version 0.0.1-rc16
                    
#r "nuget: RhoMicro.RazorTemplating, 0.0.1-rc16"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package RhoMicro.RazorTemplating@0.0.1-rc16
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=RhoMicro.RazorTemplating&version=0.0.1-rc16&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=RhoMicro.RazorTemplating&version=0.0.1-rc16&prerelease
                    
Install as a Cake Tool

RhoMicro.RazorTemplating

This is a library for compiling razor templates at runtime.

This package uses an unsupported and unofficial dependency for obtaining the RazorSourceGenerator used when compiling razor templates. This means that razor language features past net8 are not necessarily supported and may not be downstreamed from the razor toolchain in the future.

Licensing

This work is licensed to you under the MPL-2.0 license.

Features

  • dynamically compile razor source texts at runtime
  • manage interdependent razor templates (Layout, MyReusableComponent etc.)
  • provide your own template providers for flexible retrieval from any data source
  • cached compilation of templates (using IMemoryCache) for fast (amortized) rendering

Installation

CLI:

dotnet add package RhoMicro.RazorTemplating

How To Use

Simple Use Cases

Use the rendering façade:

using RhoMicro.RazorTemplating;

var html = await RazorTemplateRenderer.Render(
    // Razor source text to render:
    """
    <div>
        Hello, @(Name)!
    </div>

    @code
    {
        [Parameter] public string Name { get; set; } = "World";
    }
    """,
    // Collection of parameters to pass to the component:
    [new("Name", "SleepWellPupper")]);

// html contains:
// <div>
//     Hello, SleepWellPupper!
// </div>

Custom Use Cases

Integrate into your DI-container:

using RhoMicro.RazorTemplating;

services.AddRazorTemplating();

Provide an implementation of IRazorTemplateProvider to allow for template discovery:

using RhoMicro.RazorTemplating;

services.AddScoped<IRazorTemplateProvider, MyRazorTemplateProvider>();

public class MyRazorTemplateProvider(MyDbContext db)
    : IRazorTemplateProvider
{
    public async ValueTask<RazorTemplate> LoadTemplate(
        String name,
        CancellationToken ct = default)
    {
        var template = await db.MailTemplates.FindAsync(name);
        var result = RazorTemplate.Create(
            name,
            template.Text);
        
        return result;
    }    
}

An implementation for in-memory definition of templates is provided by the library:

using RhoMicro.RazorTemplating;

services.AddSingleton<IRazorTemplateProvider>(
    new InMemoryRazorTemplateProvider(
        RazorTemplate.Create("Template1", "<div>source text here</div>"),
        RazorTemplate.Create("Template2", "<div>source text here</div>")));

Define options for compiling templates:

using RhoMicro.RazorTemplating;

services.AddSingleton(new RazorTemplateCompilerOptions(
    // Root namespace used when compiling templates:
    RootNamespace: "MyTemplates",
    // When compiling, diagnostics with this severity or higher are logged:
    MinimumLoggingDiagnosticSeverity: DiagnosticSeverity.Error,
    // Using statement parts used in `gloabl using {0};` statements:
    GlobalUsings: 
    [
        "MyTemplates.Utilities",
        "static MyTemplates.StaticHelperClass"
    ],
    // Assemblies to be referenced when compiling templates:
    ReferenceAssemblies:
    [
        typeof(MySharedComponentLibrary.SharedComponent).Assembly
    ]));

Configure caching of compiled templates by registering an implementation of IMemoryCacheEntryConfiguration:

using RhoMicro.RazorTemplating;

services.AddSingleton<IMemoryCacheEntryConfiguration, MyMemoryCacheEntryConfiguration>();

public class MyMemoryCacheEntryConfiguration : IMemoryCacheEntryConfiguration
{
    public async ValueTask Configure(ICacheEntry entry, RazorTemplate template)
    {
        entry.SlidingExpiration = TimeSpan.FromHours(1);
    }
}

Inject an instance of IRazorTemplateRenderer to render templates:

using RhoMicro.RazorTemplating;

public class MyEmailService(
    IEmailClient client,
    IRazorTemplateRenderer renderer)
{
    public async Task SendEmail(CancellationToken ct)
    {
        var text = await renderer.Render(
            // The name of the template to render:
            "MyEmailTemplate",
            // Parameters to pass to the razor component:
            [
                new("Name", "John Doe"),
                new("Date", DateTime.Now)
            ],
            ct);
        
        await client.SendEmail(text, "john.doe@aol.com");
    }
}

Define inter-template dependencies for reusability:

using RhoMicro.RazorTemplating;

var myLayout = RazorTemplate.Create(
    "Layout",
    """
    @namespace MyTemplates
    <outer>@(ChildContent)</outer>
    
    @code
    {
        [Parameter]
        public RenderFragment? ChildContent { get; set; }
    }
    """);
var myTemplate = RazorTemplate.Create(
    "Template",
    """
    <MyTemplates.Layout>
        <inner>foo</inner>
    </MyTemplates.Layout>
    """,
    dependencis: ["Layout"])

Lifetimes And Caching

RazorTemplate objects own and manage the compiled template type, but they are managed by a cache. Consumer code should not dispose them manually. For example, the InMemoryRazorTemplateProvider will dispose all registered templates upon disposal. Likewise, the cache does not need to register a disposal callback to cache entries.

By default, cache entries do not expire.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.0.1-rc16 35 5/15/2026
0.0.1-rc15 34 5/15/2026
0.0.1-rc14 36 5/15/2026
0.0.1-rc13 34 5/15/2026
0.0.1-rc12 31 5/15/2026
0.0.1-rc11 40 5/15/2026