### Install RazorEngineCore via NuGet Source: https://github.com/adoconnection/razorenginecore/blob/master/README.md The command to install the RazorEngineCore package into your .NET project using the NuGet Package Manager. ```powershell Install-Package RazorEngineCore ``` -------------------------------- ### Custom HtmlHelper Implementation for RazorEngine Source: https://github.com/adoconnection/razorenginecore/wiki/@Html-implementation-example This example demonstrates creating a custom HtmlHelper class and a base template class to enable @Html syntax within RazorEngine templates. It includes a sample Hidden input generator that handles model expressions. ```csharp public class TestModel { public string StudentId { get; set; } } public class MvcTemplate : RazorEngineTemplateBase { public MyHtmlHelper Html { get; set; } } public class MyHtmlHelper { private readonly MvcTemplate templateInstance; public MyHtmlHelper(MvcTemplate templateInstance) { this.templateInstance = templateInstance; } public string Hidden(Expression> selector) { object propertyValue = selector.Compile()(this.templateInstance.Model); MemberExpression body = (MemberExpression)selector.Body; string name = HttpUtility.HtmlAttributeEncode(body.Member.Name); string value = HttpUtility.HtmlAttributeEncode(propertyValue?.ToString() ?? ""); return $""; } } class Program { static void Main(string[] args) { string content = @"

hidden: @Html.Hidden(m => m.StudentId)

"; RazorEngine razorEngine = new RazorEngine(); var compiledTemplate = razorEngine.Compile>(content); string result = compiledTemplate.Run(template => { template.Model = new TestModel() { StudentId = "" }; template.Html = new MyHtmlHelper(template); }); Console.WriteLine(result); } } ``` -------------------------------- ### RazorEngineCompilationException Example Source: https://github.com/adoconnection/razorenginecore/wiki/@model-and-Visual-Studio-IntelliSense An example of the compilation error thrown when using the unsupported @model syntax in a template. ```text RazorEngineCore.RazorEngineCompilationException Unable to compile template: j2rpxc2v.45u(7,7): error CS0103: The name 'model' does not exist in the current context at RazorEngineCore.RazorEngine.CreateAndCompileToStream(String templateSource, RazorEngineCompilationOptions options) at RazorEngineCore.RazorEngine.Compile[T](String content, Action`1 builderAction) ``` -------------------------------- ### RazorEngine Default Behavior Example Source: https://github.com/adoconnection/razorenginecore/wiki/@Raw Demonstrates the default behavior of RazorEngine where values are not automatically HTML encoded. This requires manual escaping or using a helper like @Raw. ```cs IRazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate template = razorEngine.Compile("Hello @Model.Name"); string result = template.Run(new { Name = "Test" }); Console.WriteLine(result); ``` -------------------------------- ### RazorEngine HtmlSafeTemplate Usage Source: https://github.com/adoconnection/razorenginecore/wiki/@Raw Shows how to use the HtmlSafeTemplate to ensure that model properties are HTML encoded by default, while providing a mechanism (@Raw) to bypass encoding when necessary. This example highlights the difference in output for safe and raw content. ```cs RazorEngine razorEngine = new RazorEngine(); var razorEngineCompiledTemplate = razorEngine.Compile( "
This is now safe: @Model.FirstName
\n" + "
but not this: @Raw(Model.FirstName)
"); string result = razorEngineCompiledTemplate.Run(instance => { instance.Model = new AnonymousTypeWrapper(new { FirstName = "", LastName = "123" }); }); Console.WriteLine(result); ``` -------------------------------- ### Basic Template Rendering Source: https://github.com/adoconnection/razorenginecore/blob/master/README.md Demonstrates how to initialize the engine, compile a simple string template, and execute it with an anonymous object model. ```csharp IRazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate template = razorEngine.Compile("Hello @Model.Name"); string result = template.Run(new { Name = "Alexander" }); Console.WriteLine(result); ``` -------------------------------- ### Layout and Include Implementation Source: https://context7.com/adoconnection/razorenginecore/llms.txt Demonstrates how to implement @Include and @Layout functionality by creating a custom template base class with callback delegates for template composition. ```APIDOC ## Layout and Include Implementation ### Description This implementation uses a custom `RazorEngineTemplateBase` to define `Include` and `RenderBody` methods, allowing for master layout wrapping and partial template inclusion. ### Implementation Details - **Base Class**: `LayoutTemplateBase` inherits from `RazorEngineTemplateBase`. - **Callbacks**: Uses `Func` for partial inclusion and `Func` for rendering body content. ### Usage Example ```csharp // Define the template base public class LayoutTemplateBase : RazorEngineTemplateBase { public Func IncludeCallback { get; set; } public Func RenderBodyCallback { get; set; } public string Layout { get; set; } public string Include(string key, object model = null) => IncludeCallback(key, model); public string RenderBody() => RenderBodyCallback(); } ``` ``` -------------------------------- ### RazorEngineCore: Implement Include and Layout with Custom Base Class Source: https://context7.com/adoconnection/razorenginecore/llms.txt Demonstrates how to implement `@Include()` and `@Layout` functionality by creating a custom template base class. This enables template composition with partials and master layouts, allowing for reusable template structures. It requires the RazorEngineCore library. ```csharp using RazorEngineCore; public class LayoutTemplateBase : RazorEngineTemplateBase { public Func IncludeCallback { get; set; } public Func RenderBodyCallback { get; set; } public string Layout { get; set; } public string Include(string key, object model = null) { return IncludeCallback(key, model); } public string RenderBody() { return RenderBodyCallback(); } } // Compile main template and partials IRazorEngine razorEngine = new RazorEngine(); var mainTemplate = razorEngine.Compile( "@{ Layout = \"master\"; }

@Model.Title

@Include(\"footer\", Model)" ); var partials = new Dictionary> { ["master"] = razorEngine.Compile( " @RenderBody() " ), ["footer"] = razorEngine.Compile( "
Copyright @Model.Year
" ) }; // Run with layout support string RunWithLayout(IRazorEngineCompiledTemplate template, object model) { LayoutTemplateBase templateRef = null; string content = template.Run(instance => { instance.Model = new AnonymousTypeWrapper(model); instance.IncludeCallback = (key, m) => RunWithLayout(partials[key], m ?? model); templateRef = instance; }); if (templateRef?.Layout != null) { return partials[templateRef.Layout].Run(instance => { instance.Model = new AnonymousTypeWrapper(model); instance.RenderBodyCallback = () => content; instance.IncludeCallback = (key, m) => RunWithLayout(partials[key], m ?? model); }); } return content; } string result = RunWithLayout(mainTemplate, new { Title = "Welcome", Year = 2024 }); Console.WriteLine(result); // Output: // // // //

Welcome

//
Copyright 2024
// // ``` -------------------------------- ### Compile and Run with RazorEngineTemplateBase Source: https://github.com/adoconnection/razorenginecore/wiki/Strongly-typed-model Demonstrates how to compile a string template using the standard RazorEngineTemplateBase and execute it by providing a model instance. ```csharp IRazorEngine razorEngine = new RazorEngine(); string content = "Hello @Model.Name"; IRazorEngineCompiledTemplate> template = razorEngine.Compile>(content); string result = template.Run(instance => { instance.Model = new TestModel() { Name = "Hello", Items = new[] {3, 1, 2} }; }); Console.WriteLine(result); ``` -------------------------------- ### Configure Razor Project Engine Source: https://context7.com/adoconnection/razorenginecore/llms.txt Demonstrates how to customize the Razor engine configuration, including setting namespaces, adding assembly references, and registering custom features. ```APIDOC ## Configure Razor Project Engine ### Description Allows for the modification of the underlying RazorProjectEngineBuilder. This is used to register custom features, define root namespaces, add assembly references, and include default usings for the template compilation process. ### Method Compile(string, Action) ### Parameters - **builder** (Action) - A delegate used to configure the compilation options. - **builder.ConfigureRazorEngineProject** (Action) - Used to set project-level settings like RootNamespace. - **builder.AddAssemblyReference** (Method) - Adds necessary assemblies for the template to reference. - **builder.AddUsing** (Method) - Adds global using statements to the generated template code. ### Request Example ```csharp razorEngine.Compile(templateString, builder => { builder.ConfigureRazorEngineProject(projectBuilder => projectBuilder.SetRootNamespace("MyApp")); builder.AddAssemblyReference(typeof(System.Text.Json.JsonSerializer)); builder.AddUsing("System.Text.Json"); });``` ``` -------------------------------- ### Render Templates with Classic RazorEngine Source: https://github.com/adoconnection/razorenginecore/wiki/Switch-from-RazorEngine-cshtml-templates Demonstrates the legacy approach of checking the internal cache and compiling templates on the fly using the static Engine.Razor instance. ```csharp 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); } ``` -------------------------------- ### Configure RazorProjectEngine for Custom Templates Source: https://context7.com/adoconnection/razorenginecore/llms.txt Shows how to use the builder pattern to configure the RazorProjectEngine, including setting the root namespace, adding assembly references, and including default namespaces for templates. ```csharp using RazorEngineCore; using Microsoft.AspNetCore.Razor.Language; IRazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate template = razorEngine.Compile( "

@Model.Title

", builder => { builder.ConfigureRazorEngineProject(projectBuilder => { projectBuilder.SetRootNamespace("MyApp.Templates"); }); builder.AddAssemblyReference(typeof(System.Text.Json.JsonSerializer)); builder.AddUsing("System.Text.Json"); } ); string result = template.Run(new { Title = "Configured Template" }); Console.WriteLine(result); ``` -------------------------------- ### RazorEngine Compile with Parts and Layouts (C#) Source: https://github.com/adoconnection/razorenginecore/wiki/@Include-and-@Layout This code snippet shows how to compile a main Razor template along with a dictionary of partial templates (parts) that can be included or used as layouts. It utilizes a custom `MyTemplateBase` and an extension method to manage the compilation and execution of these related templates. ```csharp namespace ConsoleApp11 { class Program { static void Main(string[] args) { string template = @"@{ Layout = \"MyLayout\"; }

@Model.Title

@Include(\"outer\", Model) "; IDictionary parts = new Dictionary() { {"MyLayout", @" LAYOUT HEADER @RenderBody() LAYOUT FOOTER "}, {"outer", "This is Outer include, <@Model.Title>, @Include(\"inner\")"}, {"inner", "This is Inner include"} }; IRazorEngine razorEngine = new RazorEngine(); MyCompiledTemplate compiledTemplate = razorEngine.Compile(template, parts); string result = compiledTemplate.Run(new {Title = "Hello"}); Console.WriteLine(result); Console.ReadKey(); } } } ``` -------------------------------- ### Asynchronous Template Compilation and Execution in C# Source: https://context7.com/adoconnection/razorenginecore/llms.txt Shows how to use asynchronous methods for compiling and running Razor templates. Supports cancellation tokens for managing long-running operations. ```csharp using RazorEngineCore; IRazorEngine razorEngine = new RazorEngine(); // Async compile with cancellation support CancellationTokenSource cts = new CancellationTokenSource(); IRazorEngineCompiledTemplate template = await razorEngine.CompileAsync( "Hello @Model.Name from async compilation!", cancellationToken: cts.Token ); // Async run string result = await template.RunAsync(new { Name = "World" }); Console.WriteLine(result); // Output: Hello World from async compilation! ``` -------------------------------- ### Add Assembly References to RazorEngineCore Templates Source: https://context7.com/adoconnection/razorenginecore/llms.txt Demonstrates how to use IRazorEngineCompilationOptionsBuilder to include external assemblies or namespaces. This is necessary when templates require access to types not included by default. ```csharp using RazorEngineCore; using System.Reflection; IRazorEngine razorEngine = new RazorEngine(); string templateText = @" @using System.IO @using System.Security.Cryptography

Current Directory: @Directory.GetCurrentDirectory()

Random GUID: @Guid.NewGuid()

"; IRazorEngineCompiledTemplate compiledTemplate = razorEngine.Compile(templateText, builder => { builder.AddAssemblyReferenceByName("System.Security"); builder.AddAssemblyReference(typeof(System.IO.File)); builder.AddAssemblyReference(Assembly.GetExecutingAssembly()); builder.AddUsing("System.Text"); }); string result = compiledTemplate.Run(new { }); Console.WriteLine(result); ``` -------------------------------- ### Save and Load Compiled Templates Source: https://github.com/adoconnection/razorenginecore/blob/master/README.md Demonstrates how to persist compiled templates to disk or memory streams to avoid redundant compilation overhead. This is essential for performance in high-traffic applications. ```csharp IRazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate template = razorEngine.Compile("Hello @Model.Name"); // save to file template.SaveToFile("myTemplate.dll"); //save to stream MemoryStream memoryStream = new MemoryStream(); template.SaveToStream(memoryStream); // Load from file/stream IRazorEngineCompiledTemplate template1 = RazorEngineCompiledTemplate.LoadFromFile("myTemplate.dll"); IRazorEngineCompiledTemplate template2 = RazorEngineCompiledTemplate.LoadFromStream(myStream); // Load with custom base class IRazorEngineCompiledTemplate template3 = RazorEngineCompiledTemplate.LoadFromFile("myTemplate.dll"); ``` -------------------------------- ### Strongly Typed Models with RazorEngineCore in C# Source: https://context7.com/adoconnection/razorenginecore/llms.txt Illustrates compiling and executing Razor templates using strongly-typed models. This approach enhances IntelliSense and provides compile-time type checking. A custom model class is defined and used. ```csharp using RazorEngineCore; public class UserModel { public string Name { get; set; } public string Email { get; set; } public int[] Scores { get; set; } } // Compile with strongly typed model IRazorEngine razorEngine = new RazorEngine(); string templateText = @"@* Using @*@ for verbatim string literal in C# *

Hello @Model.Name

Email: @Model.Email

    @foreach(var score in Model.Scores) {
  • Score: @score
  • }
"; IRazorEngineCompiledTemplate> template = razorEngine.Compile>(templateText); string result = template.Run(instance => { instance.Model = new UserModel { Name = "John Doe", Email = "john@example.com", Scores = new[] { 95, 87, 92 } }; }); Console.WriteLine(result); // Output: //

Hello John Doe

//

Email: john@example.com

//
    //
  • Score: 95
  • //
  • Score: 87
  • //
  • Score: 92
  • //
``` -------------------------------- ### Basic Template Compilation and Execution in C# Source: https://context7.com/adoconnection/razorenginecore/llms.txt Demonstrates how to compile a Razor template string and execute it with an anonymous model. The template uses '@Model.PropertyName' to access properties of the provided model. ```csharp using RazorEngineCore; // Create engine instance and compile template IRazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate template = razorEngine.Compile("Hello @Model.Name, you have @Model.Count items."); // Run template with anonymous model string result = template.Run(new { Name = "Alexander", Count = 5 }); Console.WriteLine(result); // Output: Hello Alexander, you have 5 items. ``` -------------------------------- ### Custom Template Base with Helper Methods in C# Source: https://context7.com/adoconnection/razorenginecore/llms.txt Demonstrates extending RazorEngineCore by creating a custom template base class. This allows adding custom properties and helper methods that can be directly used within Razor templates. ```csharp using RazorEngineCore; public class CustomTemplate : RazorEngineTemplateBase { public int A { get; set; } public string B { get; set; } public string Decorator(object value) { return "-=" + value + "=-}; } public string FormatCurrency(decimal amount) { return "$" + amount.ToString("N2"); } } // Compile with custom template base IRazorEngine razorEngine = new RazorEngine(); string content = @"@* Using @*@ for verbatim string literal in C# * Values: @A, @B, @Decorator(123), @FormatCurrency(99.5m)"; IRazorEngineCompiledTemplate template = razorEngine.Compile(content); string result = template.Run(instance => { instance.A = 10; instance.B = "Alex"; }); Console.WriteLine(result); // Output: Values: 10, Alex, -=123=-, $99.50 ``` -------------------------------- ### RazorEngineCore: Implement Custom HTML Helpers with MvcTemplate Source: https://context7.com/adoconnection/razorenginecore/llms.txt Shows how to implement MVC-style `@Html` helpers by creating a custom template base class with an `HtmlHelper` property. This allows for familiar patterns like `@Html.Hidden()` or `@Html.TextBox()` within templates. It depends on RazorEngineCore and System.Web for HTML encoding. ```csharp using RazorEngineCore; using System.Linq.Expressions; using System.Web; public class TestModel { public string StudentId { get; set; } public string Email { get; set; } } public class MvcTemplate : RazorEngineTemplateBase { public MyHtmlHelper Html { get; set; } } public class MyHtmlHelper { private readonly MvcTemplate _template; public MyHtmlHelper(MvcTemplate template) { _template = template; } public string Hidden(Expression> selector) { object value = selector.Compile()(_template.Model); MemberExpression body = (MemberExpression)selector.Body; string name = HttpUtility.HtmlAttributeEncode(body.Member.Name); string encodedValue = HttpUtility.HtmlAttributeEncode(value?.ToString() ?? ""); return $""; } public string TextBox(Expression> selector) { object value = selector.Compile()(_template.Model); MemberExpression body = (MemberExpression)selector.Body; string name = HttpUtility.HtmlAttributeEncode(body.Member.Name); string encodedValue = HttpUtility.HtmlAttributeEncode(value?.ToString() ?? ""); return $""; } } // Usage IRazorEngine razorEngine = new RazorEngine(); string content = @"
@Html.Hidden(m => m.StudentId) @Html.TextBox(m => m.Email)
"; var template = razorEngine.Compile>(content); string result = template.Run(instance => { instance.Model = new TestModel { StudentId = "12345", Email = "test@example.com" }; instance.Html = new MyHtmlHelper(instance); }); Console.WriteLine(result); // Output: //
// // //
``` -------------------------------- ### Define and Execute Custom Template Base Source: https://github.com/adoconnection/razorenginecore/wiki/Strongly-typed-model Shows how to create a custom template base class inheriting from RazorEngineTemplateBase to introduce custom logic and properties, followed by its compilation and execution. ```csharp public class CustomTemplateBase : RazorEngineTemplateBase { public int A { get; set; } public string B { get; set; } public new MyModel Model { get; set; } public string Decorator(object value) { return "-=" + value + "=-"; } } string content = @"Hello @A, @B, @Decorator(123) @Model.Membership.Level"; IRazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate template = razorEngine.Compile(content); string result = template.Run(instance => { instance.A = 10; instance.B = "Alex"; instance.Model = model; }); Console.WriteLine(result); ``` -------------------------------- ### Injecting Localizer via Initialization Method in RazorEngineCore Source: https://github.com/adoconnection/razorenginecore/wiki/@Inject-and-referencing-other-assemblies Shows an alternative approach using an initialization method to inject dependencies into a custom template base class. This encapsulates the dependency and provides a cleaner interface for the template. ```csharp public class MyTemplateBase : RazorEngineTemplateBase { private IStringLocalizer localizer; public void Initialize(IStringLocalizer localizer) { this.localizer = localizer; } public string Localize(string key) { return this.localizer[key]; } } string templateText = @"

@Localize(""Header"")

"; IRazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate compiledTemplate = razorEngine.Compile(templateText); string result = compiledTemplate.Run(instance => { instance.Initialize(this.localizerInstance); }); ``` -------------------------------- ### Implement Manual Caching in RazorEngineCore Source: https://github.com/adoconnection/razorenginecore/wiki/Switch-from-RazorEngine-cshtml-templates Shows how to implement a thread-safe ConcurrentDictionary cache for compiled templates in RazorEngineCore, as the library does not provide an automatic global cache. ```csharp private static ConcurrentDictionary TemplateCache = new ConcurrentDictionary(); 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); ``` -------------------------------- ### Implement HTML-Safe Templates with XSS Protection Source: https://context7.com/adoconnection/razorenginecore/llms.txt Create a custom template base class that overrides Write methods to automatically HTML-encode output. Includes a Raw helper method to bypass encoding for trusted content. ```csharp using RazorEngineCore; public class HtmlSafeTemplate : RazorEngineTemplateBase { class RawContent { public object Value { get; set; } public RawContent(object value) { Value = value; } } public object Raw(object value) { return new RawContent(value); } public override void Write(object obj = null) { object value = obj is RawContent rawContent ? rawContent.Value : System.Text.Encodings.Web.HtmlEncoder.Default.Encode(obj?.ToString() ?? string.Empty); base.Write(value); } public override void WriteAttributeValue(string prefix, int prefixOffset, object value, int valueOffset, int valueLength, bool isLiteral) { value = value is RawContent rawContent ? rawContent.Value : System.Text.Encodings.Web.HtmlEncoder.Default.Encode(value?.ToString() ?? string.Empty); base.WriteAttributeValue(prefix, prefixOffset, value, valueOffset, valueLength, isLiteral); } } ``` -------------------------------- ### Custom @Html Helper Implementation Source: https://context7.com/adoconnection/razorenginecore/llms.txt Shows how to create MVC-style HTML helpers in RazorEngineCore by injecting a helper class into the template base. ```APIDOC ## Custom @Html Helper Implementation ### Description Enables the use of familiar MVC syntax like `@Html.TextBox()` by creating a generic `MvcTemplate` base class and a corresponding `MyHtmlHelper` class. ### Implementation Details - **Template Base**: `MvcTemplate` provides an `Html` property. - **Helper Logic**: `MyHtmlHelper` uses expression trees to extract property names and values from the model for generating HTML tags. ### Usage Example ```csharp // Template usage var template = razorEngine.Compile>(content); string result = template.Run(instance => { instance.Model = new TestModel { StudentId = "12345" }; instance.Html = new MyHtmlHelper(instance); }); ``` ``` -------------------------------- ### Strongly Typed Model Usage Source: https://github.com/adoconnection/razorenginecore/blob/master/README.md Shows how to compile a template using a specific model type, providing better type safety and intellisense support within the template. ```csharp IRazorEngine razorEngine = new RazorEngine(); string templateText = "Hello @Model.Name"; IRazorEngineCompiledTemplate> template = razorEngine.Compile>(templateText); string result = template.Run(instance => { instance.Model = new TestModel() { Name = "Hello", Items = new[] {3, 1, 2} }; }); Console.WriteLine(result); ``` -------------------------------- ### Adding Assembly References Source: https://context7.com/adoconnection/razorenginecore/llms.txt Demonstrates how to add assembly references to the RazorEngine compilation options, allowing templates to access types from external assemblies by name, type, or Assembly object. ```APIDOC ## Adding Assembly References Use `IRazorEngineCompilationOptionsBuilder` to add assembly references when templates need access to types from external assemblies. References can be added by name, type, or Assembly object. ```csharp using RazorEngineCore; using System.Reflection; IRazorEngine razorEngine = new RazorEngine(); string templateText = @"\n@using System.IO\n@using System.Security.Cryptography\n\n

Current Directory: @Directory.GetCurrentDirectory()

\n

Random GUID: @Guid.NewGuid()

"; IRazorEngineCompiledTemplate compiledTemplate = razorEngine.Compile(templateText, builder => { // Add by assembly name builder.AddAssemblyReferenceByName("System.Security"); // Add by type (also adds type's assembly) builder.AddAssemblyReference(typeof(System.IO.File)); // Add by Assembly object builder.AddAssemblyReference(Assembly.GetExecutingAssembly()); // Add default using namespace builder.AddUsing("System.Text"); }); string result = compiledTemplate.Run(new { }); Console.WriteLine(result); // Output: //

Current Directory: /app

//

Random GUID: 550e8400-e29b-41d4-a716-446655440000

``` ``` -------------------------------- ### HtmlSafeTemplate Implementation for .NET 5+ Source: https://github.com/adoconnection/razorenginecore/wiki/@Raw Provides the C# implementation of the HtmlSafeTemplate class for .NET 5 and later. It utilizes System.Text.Encodings.Web.HtmlEncoder for encoding and includes a Raw helper to bypass encoding. ```cs public class HtmlSafeTemplate : RazorEngineTemplateBase { class RawContent { public object Value { get; set; } public RawContent(object value) { Value = value; } } public object Raw(object value) { return new RawContent(value); } public override void Write(object obj = null) { object value = obj is RawContent rawContent ? rawContent.Value : System.Text.Encodings.Web.HtmlEncoder.Default.Encode(obj?.ToString() ?? string.Empty); base.Write(value); } public override void WriteAttributeValue(string prefix, int prefixOffset, object value, int valueOffset, int valueLength, bool isLiteral) { value = value is RawContent rawContent ? rawContent.Value : System.Text.Encodings.Web.HtmlEncoder.Default.Encode(value?.ToString() ?? string.Empty); base.WriteAttributeValue(prefix, prefixOffset, value, valueOffset, valueLength, isLiteral); } } ``` -------------------------------- ### RazorEngine Extension for Compiling Templates with Parts (C#) Source: https://github.com/adoconnection/razorenginecore/wiki/@Include-and-@Layout Provides an extension method `Compile` for the `RazorEngine` class. This method allows compiling a primary template along with a dictionary of other templates (parts), enabling the use of `@Include` and `@Layout` functionalities by pre-compiling all related templates. ```csharp public static class RazorEngineCoreExtensions { public static MyCompiledTemplate Compile(this RazorEngine razorEngine, string template, IDictionary parts) { return new MyCompiledTemplate( razorEngine.Compile(template), parts.ToDictionary( k => k.Key, v => razorEngine.Compile(v.Value))); } } ``` -------------------------------- ### Debugging Razor Templates Source: https://github.com/adoconnection/razorenginecore/blob/master/README.md Illustrates how to enable debugging information during compilation and runtime, allowing the use of breakpoints within the template. ```csharp IRazorEngineCompiledTemplate template2 = razorEngine.Compile(templateText, builder => { builder.IncludeDebuggingInfo(); }); template2.EnableDebugging(); string result = template2.Run(new { Title = "Welcome" }); ``` -------------------------------- ### Enable Template Debugging in RazorEngineCore Source: https://context7.com/adoconnection/razorenginecore/llms.txt Shows how to enable debugging support to step through templates in Visual Studio. It requires calling IncludeDebuggingInfo during compilation and EnableDebugging before execution. ```csharp using RazorEngineCore; IRazorEngine razorEngine = new RazorEngine(); string templateText = @"

Debug Example

@{ var items = new[] { "Apple", "Banana", "Cherry" }; } @foreach(var item in items) { @{ Breakpoint(); }

Item: @item

}"; IRazorEngineCompiledTemplate template = razorEngine.Compile(templateText, builder => { builder.IncludeDebuggingInfo(); }); template.EnableDebugging(); string result = template.Run(new { Title = "Welcome" }); Console.WriteLine(result); ``` -------------------------------- ### Save and Load Compiled Templates Source: https://context7.com/adoconnection/razorenginecore/llms.txt Demonstrates how to persist compiled Razor templates to files or streams to avoid repeated compilation overhead in production environments. ```csharp IRazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate template = razorEngine.Compile("Hello @Model.Name"); // Save to file template.SaveToFile("myTemplate.dll"); // Save to stream MemoryStream memoryStream = new MemoryStream(); template.SaveToStream(memoryStream); memoryStream.Position = 0; // Load from file IRazorEngineCompiledTemplate loadedFromFile = RazorEngineCompiledTemplate.LoadFromFile("myTemplate.dll"); // Load from stream IRazorEngineCompiledTemplate loadedFromStream = RazorEngineCompiledTemplate.LoadFromStream(memoryStream); ``` -------------------------------- ### Handling Compilation Errors Source: https://context7.com/adoconnection/razorenginecore/llms.txt Explains how to catch and inspect RazorEngineCompilationException to debug template syntax errors and view generated C# code. ```APIDOC ## Handling Compilation Errors ### Description When a Razor template fails to compile, the library throws a RazorEngineCompilationException. This endpoint/method allows developers to access detailed compiler diagnostics, error locations, and the generated C# source code for debugging purposes. ### Method N/A (Exception Handling) ### Parameters - **ex** (RazorEngineCompilationException) - The exception object caught during the `razorEngine.Compile()` call. ### Response - **ex.Errors** (IEnumerable) - A collection of compiler errors containing Severity, Message, and Location. - **ex.GeneratedCode** (string) - The full C# source code generated from the template, useful for identifying syntax issues. ### Example ```csharp try { IRazorEngineCompiledTemplate template = razorEngine.Compile(invalidTemplate); } catch (RazorEngineCompilationException ex) { /* Access ex.Errors or ex.GeneratedCode */ }``` ``` -------------------------------- ### HtmlSafeTemplate Implementation for .NET 4.7.2 Source: https://github.com/adoconnection/razorenginecore/wiki/@Raw Provides the C# implementation of the HtmlSafeTemplate class for .NET Framework 4.7.2. It uses System.Web.HttpUtility for encoding and includes a Raw helper to bypass encoding. ```cs public class HtmlSafeTemplate : RazorEngineTemplateBase { class RawContent { public object Value { get; set; } public RawContent(object value) { Value = value; } } public object Raw(object value) { return new RawContent(value); } public override void Write(object obj = null) { object value = obj is RawContent rawContent ? rawContent.Value : System.Web.HttpUtility.HtmlEncode(obj); base.Write(value); } public override void WriteAttributeValue(string prefix, int prefixOffset, object value, int valueOffset, int valueLength, bool isLiteral) { value = value is RawContent rawContent ? rawContent.Value : System.Web.HttpUtility.HtmlAttributeEncode(value?.ToString()); base.WriteAttributeValue(prefix, prefixOffset, value, valueOffset, valueLength, isLiteral); } } ``` -------------------------------- ### Handle RazorEngineCore Compilation Errors Source: https://context7.com/adoconnection/razorenginecore/llms.txt Demonstrates how to catch RazorEngineCompilationException to inspect compiler diagnostics, error locations, and the generated C# source code when a template fails to compile. ```csharp using RazorEngineCore; IRazorEngine razorEngine = new RazorEngine(); string invalidTemplate = @"

@Model.Title

@{ // Invalid C# syntax - missing semicolon var x = 5 var y = 10; }

Result: @(x + y)

"; try { IRazorEngineCompiledTemplate template = razorEngine.Compile(invalidTemplate); } catch (RazorEngineCompilationException ex) { Console.WriteLine("Compilation failed!"); Console.WriteLine($"Message: {ex.Message}"); foreach (var error in ex.Errors) { Console.WriteLine($" - {error.Severity}: {error.GetMessage()}"); Console.WriteLine($" Location: {error.Location}"); } Console.WriteLine("\nGenerated Code:"); Console.WriteLine(ex.GeneratedCode); } ``` -------------------------------- ### Custom Template Base for RazorEngine Includes (C#) Source: https://github.com/adoconnection/razorenginecore/wiki/@Include-and-@Layout Defines a custom template base class `MyTemplateBase` that extends `RazorEngineTemplateBase`. It introduces callbacks for handling template includes (`IncludeCallback`) and rendering the body of a layout (`RenderBodyCallback`), along with a property for specifying the layout template. ```csharp public class MyTemplateBase : RazorEngineTemplateBase { public Func IncludeCallback { get; set; } public Func RenderBodyCallback { get; set; } public string Layout { get; set; } public string Include(string key, object model = null) { return this.IncludeCallback(key, model); } public string RenderBody() { return this.RenderBodyCallback(); } } ``` -------------------------------- ### Define Template Functions and Custom Members Source: https://github.com/adoconnection/razorenginecore/blob/master/README.md Shows how to define reusable functions within Razor templates and how to extend templates using custom base classes to provide helper methods. ```csharp public class CustomTemplate : RazorEngineTemplateBase { public int A { get; set; } public string B { get; set; } public string Decorator(object value) => "-=" + value + "=-"; } // Usage IRazorEngine razorEngine = new RazorEngine(); var template = razorEngine.Compile("Hello @A, @B, @Decorator(123)"); string result = template.Run(instance => { instance.A = 10; instance.B = "Alex"; }); ``` -------------------------------- ### Template Debugging Source: https://context7.com/adoconnection/razorenginecore/llms.txt Explains how to enable debugging for Razor templates, allowing you to step through template execution in Visual Studio by compiling with `IncludeDebuggingInfo()` and calling `EnableDebugging()`. ```APIDOC ## Template Debugging Enable debugging to step through templates in Visual Studio. Compile with `IncludeDebuggingInfo()` and call `EnableDebugging()` before running. Use `@{ Breakpoint(); }` in templates to set breakpoints. ```csharp using RazorEngineCore; IRazorEngine razorEngine = new RazorEngine(); string templateText = @"\n

Debug Example

\n@{ var items = new[] { \"Apple\", \"Banana\", \"Cherry\" }; } @foreach(var item in items) { @{ Breakpoint(); }

Item: @item

"; // Compile with debugging info IRazorEngineCompiledTemplate template = razorEngine.Compile(templateText, builder => { builder.IncludeDebuggingInfo(); }); // Enable debugging - writes template source to output directory template.EnableDebugging(); // or template.EnableDebugging("C:/MyDebugPath"); string result = template.Run(new { Title = "Welcome" }); Console.WriteLine(result); // When running in debugger, execution will pause at each Breakpoint() call ``` ``` -------------------------------- ### Reference External Assemblies Source: https://github.com/adoconnection/razorenginecore/blob/master/README.md Explains how to manually inject assembly references into the Razor compilation process when standard directives are insufficient. ```csharp IRazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate compiledTemplate = razorEngine.Compile(templateText, builder => { builder.AddAssemblyReferenceByName("System.Security"); builder.AddAssemblyReference(typeof(System.IO.File)); builder.AddAssemblyReference(Assembly.Load("source")); }); ``` -------------------------------- ### Enable Template Debugging and Run (C#) Source: https://github.com/adoconnection/razorenginecore/wiki/Debugging Enables debugging for a compiled Razor template by writing its source code to the active directory or a specified path. This allows Visual Studio to step into the template code during execution. The template is then run with provided model data. ```csharp template2.EnableDebugging(); // optional path to output directory string result = template2.Run(new { Title = "Welcome" }); ``` -------------------------------- ### Implement Thread-Safe Template Caching Source: https://github.com/adoconnection/razorenginecore/blob/master/README.md Provides a pattern for caching compiled templates using ConcurrentDictionary to ensure thread safety. This prevents re-compiling the same template multiple times. ```csharp private static ConcurrentDictionary TemplateCache = new ConcurrentDictionary(); 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); } ``` -------------------------------- ### Template Functions and Recursion Source: https://context7.com/adoconnection/razorenginecore/llms.txt Illustrates how to define and use functions within Razor templates, including recursive functions, to generate dynamic HTML content based on model data. ```APIDOC ## Template Functions and Recursion Define functions within templates using the ASP.NET Core Razor syntax. Functions can call themselves recursively and output HTML content. ```csharp using RazorEngineCore; IRazorEngine razorEngine = new RazorEngine(); string templateText = @"\n
@{ RenderTree(Model.Categories, 0); }
@{ void RenderTree(dynamic items, int level) { if (items == null) return;
    @foreach (var item in items) {
  • @item.Name @{ RenderTree(item.Children, level + 1); }
  • }
} }"; IRazorEngineCompiledTemplate template = razorEngine.Compile(templateText); string result = template.Run(new { Categories = new[] { new { Name = "Electronics", Children = new[] { new { Name = "Phones", Children = (object[])null }, new { Name = "Laptops", Children = (object[])null } }}, new { Name = "Books", Children = new[] { new { Name = "Fiction", Children = (object[])null } }} } }); Console.WriteLine(result); // Output: Nested HTML list structure ``` ``` -------------------------------- ### Adding External Assembly References in RazorEngineCore Source: https://github.com/adoconnection/razorenginecore/wiki/@Inject-and-referencing-other-assemblies Explains how to explicitly link external assemblies during the template compilation process. This is necessary when templates require types from assemblies not included by default. ```csharp IRazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate compiledTemplate = razorEngine.Compile(templateText, builder => { builder.AddAssemblyReferenceByName("System.Security"); builder.AddAssemblyReference(typeof(System.IO.File)); builder.AddAssemblyReference(Assembly.Load("source")); }); string result = compiledTemplate.Run(new { name = "Hello" }); ``` -------------------------------- ### Injecting Localizer via Public Property in RazorEngineCore Source: https://github.com/adoconnection/razorenginecore/wiki/@Inject-and-referencing-other-assemblies Demonstrates how to expose an IStringLocalizer as a public property in a custom template base class. This allows the template to access localized strings directly through the property. ```csharp public class MyTemplateBase : RazorEngineTemplateBase { public IStringLocalizer Localizer; } string templateText = @"

@Localizer[""Header""]

"; IRazorEngine razorEngine = new RazorEngine(); IRazorEngineCompiledTemplate compiledTemplate = razorEngine.Compile(templateText); string result = compiledTemplate.Run(instance => { instance.Localizer = this.localizerInstance; }); ``` -------------------------------- ### Configure RazorEngineCore Template Directives Source: https://github.com/adoconnection/razorenginecore/wiki/Switch-from-RazorEngine-cshtml-templates Explains the requirement to replace the @model directive with @inherits to maintain IntelliSense and type safety in RazorEngineCore templates. ```razor @inherits RazorEngineCore.RazorEngineTemplateBase ... ``` -------------------------------- ### Compile Template with Debugging Info (C#) Source: https://github.com/adoconnection/razorenginecore/wiki/Debugging Compiles a Razor template while including debugging information. This option generates and retains PDB files and the template's source code, essential for stepping through template logic in Visual Studio. ```csharp IRazorEngineCompiledTemplate template2 = razorEngine.Compile(templateText, builder => { builder.IncludeDebuggingInfo(); }); ``` -------------------------------- ### Compiled Template Runner for Includes and Layouts (C#) Source: https://github.com/adoconnection/razorenginecore/wiki/@Include-and-@Layout Implements `MyCompiledTemplate`, a class responsible for running Razor templates that support includes and layouts. It manages a collection of compiled partial templates and orchestrates their execution, including handling layout rendering and recursive includes. ```csharp public class MyCompiledTemplate { private readonly IRazorEngineCompiledTemplate compiledTemplate; private readonly Dictionary> compiledParts; public MyCompiledTemplate(IRazorEngineCompiledTemplate compiledTemplate, Dictionary> compiledParts) { this.compiledTemplate = compiledTemplate; this.compiledParts = compiledParts; } public string Run(object model) { return this.Run(this.compiledTemplate, model); } public string Run(IRazorEngineCompiledTemplate template, object model) { MyTemplateBase templateReference = null; string result = template.Run(instance => { if (!(model is AnonymousTypeWrapper)) { model = new AnonymousTypeWrapper(model); } instance.Model = model; instance.IncludeCallback = (key, includeModel) => this.Run(this.compiledParts[key], includeModel); templateReference = instance; }); if (templateReference.Layout == null) { return result; } return this.compiledParts[templateReference.Layout].Run(instance => { if (!(model is AnonymousTypeWrapper)) { model = new AnonymousTypeWrapper(model); } instance.Model = model; instance.IncludeCallback = (key, includeModel) => this.Run(this.compiledParts[key], includeModel); instance.RenderBodyCallback = () => result; }); } public void Save() { /* TODO this.compiledTemplate.SaveToFile(); this.compiledTemplate.SaveToStream(); foreach (var compiledPart in this.compiledParts) { compiledPart.Value.SaveToFile(); compiledPart.Value.SaveToStream(); } */ } public void Load() { // TODO } } ``` -------------------------------- ### Define Model with RazorEngineTemplateBase Source: https://github.com/adoconnection/razorenginecore/wiki/@model-and-Visual-Studio-IntelliSense Replaces the unsupported @model syntax with @inherits to define a model type for the template. This approach enables IntelliSense support within Visual Studio. ```csharp @inherits RazorEngineCore.RazorEngineTemplateBase ``` -------------------------------- ### Configure CSPROJ to Prevent Azure Functions Build Cleanup Source: https://github.com/adoconnection/razorenginecore/wiki/Azure-Functions-FileNotFoundException-workaround This configuration snippet prevents the Azure Functions build process from cleaning up required dependencies. Add this PropertyGroup to your project file to resolve the FileNotFoundException related to Microsoft.CodeAnalysis. ```xml <_FunctionsSkipCleanOutput>true ``` -------------------------------- ### Define Recursive Functions in Razor Templates Source: https://context7.com/adoconnection/razorenginecore/llms.txt Illustrates how to define local functions within a Razor template to handle recursive data structures like trees. This uses standard ASP.NET Core Razor syntax for logic and output. ```csharp using RazorEngineCore; IRazorEngine razorEngine = new RazorEngine(); string templateText = @"
@{ RenderTree(Model.Categories, 0); }
@{ void RenderTree(dynamic items, int level) { if (items == null) return;
    @foreach (var item in items) {
  • @item.Name @{ RenderTree(item.Children, level + 1); }
  • }
} }"; IRazorEngineCompiledTemplate template = razorEngine.Compile(templateText); string result = template.Run(new { Categories = new[] { new { Name = "Electronics", Children = new[] { new { Name = "Phones", Children = (object[])null }, new { Name = "Laptops", Children = (object[])null } }}, new { Name = "Books", Children = new[] { new { Name = "Fiction", Children = (object[])null } }} } }); Console.WriteLine(result); ``` -------------------------------- ### Set Breakpoint in Template (C#) Source: https://github.com/adoconnection/razorenginecore/wiki/Debugging Inserts a breakpoint within the Razor template's code. When the template is executed and reaches this line, execution will pause, allowing for debugging within the template itself. ```csharp @{ Breakpoint(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.