RazorEngineCore Documentation

repository·master·Indexed 20 days ago

https://github.com/adoconnection/razorenginecore

A modern .NET Razor template engine designed for .NET 10 and compatible versions, including .NET 5 through 9, .NET Standard 2.0, and .NET Framework 4.7.2. It provides a lightweight way to render Razor templates using anonymous or strongly typed models via RazorEngineTemplateBase. Features include template compilation, saving and loading compiled templates to files or streams, debugging support with breakpoints, and the ability to reference external assemblies.

Tokens
2.2K
Snippets
9
Records
9
Agent score
21%

What's inside RazorEngineCore

  1. Implement template caching

    master

    RazorEngineCore does not provide built-in caching. To avoid the overhead of repeated compilation, implement your own caching mechanism. A common approach is using a ConcurrentDictionary to map template identifiers (like a hash code) to IRazorEngineCompiledTemplate instances.

    private static ConcurrentDictionary<int, IRazorEngineCompiledTemplate> TemplateCache = new ConcurrentDictionary<int, IRazorEngineCompiledTemplate>();
    
    private string RenderTemplate(string template, object model)
    {
        int hashCode = template.GetHashCode();
    
        IRazorEngineCompiledTemplate compiledTemplate = TemplateCache.GetOrAdd(hashCode, i =>
        {
            RazorEngine razorEngine = new RazorEngine();
            return razorEngine.Compile(template);
        });
    
        return compiledTemplate.Run(model);
    }
  2. Install RazorEngineCore via NuGet

    master

    To use RazorEngineCore in your .NET project, install the NuGet package using the Package Manager Console.

    Supported runtimes include:

    • .NET 10
    • .NET 5, 6, 7, 8, 9
    • .NET Standard 2.0
    • .NET Framework 4.7.2

    It is compatible with Windows and Linux and supports being published as a single file.

    Install-Package RazorEngineCore
  3. Debug Razor templates

    master

    To debug templates, you must first compile them with the IncludeDebuggingInfo() option. Then, call EnableDebugging() on the compiled template. You can place @{ Breakpoint(); } anywhere in your template code to trigger a breakpoint during execution.

    IRazorEngineCompiledTemplate template2 = razorEngine.Compile(templateText, builder =>
    {
        builder.IncludeDebuggingInfo();
    });
    
    template2.EnableDebugging(); // optional path to output directory
    
    string result = template2.Run(new
    {
        Title = "Welcome"
    });
  4. Save and load compiled templates

    master

    Compiling templates is expensive. You can optimize performance by saving compiled templates to a file or stream and loading them later instead of re-compiling.

    // Saving
    IRazorEngine razorEngine = new RazorEngine();
    IRazorEngineCompiledTemplate template = razorEngine.Compile("Hello @Model.Name");
    
    template.SaveToFile("myTemplate.dll");
    
    MemoryStream memoryStream = new MemoryStream();
    template.SaveToStream(memoryStream);
    
    // Loading
    IRazorEngineCompiledTemplate template1 = RazorEngineCompiledTemplate.LoadFromFile("myTemplate.dll");
    IRazorEngineCompiledTemplate template2 = RazorEngineCompiledTemplate.LoadFromStream(myStream);
    
    // Loading with strongly typed models
    IRazorEngineCompiledTemplate<MyBase> template1 = RazorEngineCompiledTemplate<MyBase>.LoadFromFile<MyBase>("myTemplate.dll");
  5. Add helpers and custom members via RazorEngineTemplateBase

    master

    To add custom methods or properties to your template, create a class that inherits from RazorEngineTemplateBase. These members can then be accessed within the template.

    string content = @"Hello @A, @B, @Decorator(123)";
    
    IRazorEngine razorEngine = new RazorEngine();
    IRazorEngineCompiledTemplate<CustomTemplate> template = razorEngine.Compile<CustomTemplate>(content);
    
    string result = template.Run(instance =>
    {
        instance.A = 10;
        instance.B = "Alex";
    });
    
    public class CustomTemplate : RazorEngineTemplateBase
    {
        public int A { get; set; }
        public string B { get; set; }
    
        public string Decorator(object value)
        {
            return "-= " + value + " =-";
        }
    }
  6. Define template functions and recursion

    master

    You can define functions directly within the template using ASP.NET Core syntax. This allows for logic like recursion within the template markup.

    <area>
        @{ RecursionTest(3); }
    </area>
    
    @{
      void RecursionTest(int level)
      {
        if (level <= 0)
        {
            return;
        }
    
        <div LEVEL: @level</div>
        @{ RecursionTest(level - 1); }
      }
    }
  7. Basic usage with anonymous models

    master

    To perform basic template rendering, instantiate IRazorEngine, compile a template string, and then call Run passing an anonymous object as the model.

    IRazorEngine razorEngine = new RazorEngine();
    IRazorEngineCompiledTemplate template = razorEngine.Compile("Hello @Model.Name");
    
    string result = template.Run(new
    {
        Name = "Alexander"
    });
    
    Console.WriteLine(result);
  8. Use strongly typed models

    master

    For better type safety, you can compile a template against a specific class inheriting from RazorEngineTemplateBase<T>. When calling Run, use a lambda to initialize the model instance.

    IRazorEngine razorEngine = new RazorEngine();
    string templateText = "Hello @Model.Name";
    
    // Define the template type using RazorEngineTemplateBase<T>
    IRazorEngineCompiledTemplate<RazorEngineTemplateBase<TestModel>> template = razorEngine.Compile<RazorEngineTemplateBase<TestModel>>(templateText);
    
    string result = template.Run(instance =>
    {
        instance.Model = new TestModel()
        {
            Name = "Hello",
            Items = new[] {3, 1, 2}
        };
    });
    
    Console.WriteLine(result);
  9. Reference external assemblies

    master

    Standard @using statements in a template do not automatically reference external assemblies. You must use the compilation builder to manually add assembly references by name, by type, or by an existing Assembly object.

    IRazorEngine razorEngine = new RazorEngine();
    IRazorEngineCompiledTemplate compiledTemplate = razorEngine.Compile(templateText, builder =>
    {
        builder.AddAssemblyReferenceByName("System.Security"); // by name
        builder.AddAssemblyReference(typeof(System.IO.File)); // by type
        builder.AddAssemblyReference(Assembly.Load("source")); // by reference
    });
    
    string result = compiledTemplate.Run(new { name = "Hello" });