Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/adoconnection/RazorEngineCore
.NET6 Razor Template Engine
https://github.com/adoconnection/RazorEngineCore
csharp dotnet-core net5 net6 netcore31 razorengine template-engine
Last synced: about 1 month ago
JSON representation
.NET6 Razor Template Engine
- Host: GitHub
- URL: https://github.com/adoconnection/RazorEngineCore
- Owner: adoconnection
- License: mit
- Created: 2020-02-08T12:37:39.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2024-06-11T02:38:32.000Z (7 months ago)
- Last Synced: 2024-11-01T21:07:08.563Z (about 2 months ago)
- Topics: csharp, dotnet-core, net5, net6, netcore31, razorengine, template-engine
- Language: C#
- Homepage:
- Size: 215 KB
- Stars: 581
- Watchers: 12
- Forks: 86
- Open Issues: 17
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# RazorEngineCore
.NET6 Razor Template Engine. No legacy code. No breaking changes.
* .NET 6.0
* .NET 5.0
* .NET Standard 2.0
* .NET Framework 4.7.2
* Windows / Linux
* Publish as single file supported
* Thread safe
* Template debugging[![NuGet](https://img.shields.io/nuget/dt/RazorEngineCore.svg?style=flat-square)](https://www.nuget.org/packages/RazorEngineCore)
[![NuGet](https://img.shields.io/nuget/v/RazorEngineCore.svg?style=flat-square)](https://www.nuget.org/packages/RazorEngineCore)
[![Gitter](https://img.shields.io/gitter/room/RazorEngineCore/community?style=flat-square)](https://gitter.im/RazorEngineCore/community?utm_source=badge&utm_medium=badge&utm_content=badge)Every single star makes maintainer happy! ⭐
## NuGet
```
Install-Package RazorEngineCore
```## Feature requests
✅ Feel free to create new issues and vote for existing ones!## Articles
* [🚀 Piotr Bakun: How to make PDF invoice with Playwright.NET](https://bakson.dev/2022/11/10/razor-engine-core.html)
* [🚀 Christian Schou: How to send email with MailKit](https://blog.christian-schou.dk/send-emails-with-asp-net-core-with-mailkit/)
* [🚀 Dave Glick: Difference between RazorEngineCore, RazorLight and Statiq, Send email using SendGrid API](https://www.twilio.com/blog/render-emails-using-razor-templating)
* [🧑🎓 Alexander Selishchev: Building String Razor Template Engine with Bare Hands](https://www.codeproject.com/Articles/5260233/Building-String-Razor-Template-Engine-with-Bare-Ha)
* [📕 Razor syntax reference](https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-6.0)
## Wiki
* [Package comparison: RazorEngineCore / RazorLight / RazorEngine.NetCore](https://github.com/adoconnection/RazorEngineCore/wiki/Package-comparison)
* [Strongly typed model](https://github.com/adoconnection/RazorEngineCore/wiki/Strongly-typed-model)
* [@Include and @Layout](https://github.com/adoconnection/RazorEngineCore/wiki/@Include-and-@Layout)
* [@Raw](https://github.com/adoconnection/RazorEngineCore/wiki/@Raw)
* [@Inject and referencing other assemblies](https://github.com/adoconnection/RazorEngineCore/wiki/@Inject-and-referencing-other-assemblies)
* [Switch from RazorEngine cshtml templates](https://github.com/adoconnection/RazorEngineCore/wiki/Switch-from-RazorEngine-cshtml-templates)
* [Azure Functions FileNotFoundException workaround](https://github.com/adoconnection/RazorEngineCore/wiki/Azure-Functions-FileNotFoundException-workaround)
* [@Html implementation example](https://github.com/adoconnection/RazorEngineCore/wiki/@Html-implementation-example)
* [Debugging](https://github.com/adoconnection/RazorEngineCore/wiki/Debugging)
## Extensions
* [wdcossey/RazorEngineCore.Extensions](https://github.com/wdcossey/RazorEngineCore.Extensions)
- HTML values encoded by default (See [issue #65](https://github.com/adoconnection/RazorEngineCore/issues/65) and [@Raw](https://github.com/adoconnection/RazorEngineCore/wiki/@Raw))
- Template precompiling
- Direct model usage without RazorEngineTemplateBase
```cs
template.Run(object model = null)
template.RunAsync(object model = null)
template.Run(TModel model = null)
template.RunAsync(TModel model = null)
```
## :boom: HTML Safety
RazorEngineCore is not HTML safe by default. \
It can be easily turned on: see [#65](https://github.com/adoconnection/RazorEngineCore/issues/65) and [@Raw](https://github.com/adoconnection/RazorEngineCore/wiki/@Raw)## Examples
#### Basic usage
```cs
IRazorEngine razorEngine = new RazorEngine();
IRazorEngineCompiledTemplate template = razorEngine.Compile("Hello @Model.Name");string result = template.Run(new
{
Name = "Alexander"
});Console.WriteLine(result);
```#### Strongly typed model
```cs
IRazorEngine razorEngine = new RazorEngine();
string templateText = "Hello @Model.Name";// yeah, heavy definition
IRazorEngineCompiledTemplate> template = razorEngine.Compile>(templateText);string result = template.Run(instance =>
{
instance.Model = new TestModel()
{
Name = "Hello",
Items = new[] {3, 1, 2}
};
});Console.WriteLine(result);
```#### Debugging
Compile template with ```IncludeDebuggingInfo()``` option and call ```EnableDebugging()``` before running template. If template was compiled with ```IncludeDebuggingInfo()``` option, saving and loading will keep original template source code and pdb.
```cs
IRazorEngineCompiledTemplate template2 = razorEngine.Compile(templateText, builder =>
{
builder.IncludeDebuggingInfo();
});template2.EnableDebugging(); // optional path to output directory
string result = template2.Run(new
{
Title = "Welcome"
});
```
Place ```@{ Breakpoint(); }``` anywhere in template to stop at.#### Save / Load compiled templates
Most expensive task is to compile template, you should not compile template every time you need to run it
```cs
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);
``````cs
IRazorEngineCompiledTemplate template1 = RazorEngineCompiledTemplate.LoadFromFile("myTemplate.dll");
IRazorEngineCompiledTemplate template2 = RazorEngineCompiledTemplate.LoadFromStream(myStream);
``````cs
IRazorEngineCompiledTemplate template1 = RazorEngineCompiledTemplate.LoadFromFile("myTemplate.dll");
IRazorEngineCompiledTemplate template2 = RazorEngineCompiledTemplate.LoadFromStream(myStream);
```#### Caching
RazorEngineCore is not responsible for caching. Each team and project has their own caching frameworks and conventions therefore making it impossible to have builtin solution for all possible needs.If you dont have one, use following static ConcurrentDictionary example as a simplest thread safe solution.
```cs
private static ConcurrentDictionary TemplateCache = new ConcurrentDictionary();
``````cs
private string RenderTemplate(string template, object model)
{
int hashCode = template.GetHashCode();IRazorEngineCompiledTemplate compiledTemplate = TemplateCache.GetOrAdd(hashCode, i =>
{
RazorEngine razorEngine = new RazorEngine();
return razorEngine.Compile(Content);
});return compiledTemplate.Run(model);
}
```#### Template functions
ASP.NET Core way of defining template functions:
```@{ RecursionTest(3); }
@{
void RecursionTest(int level)
{
if (level <= 0)
{
return;
}
LEVEL: @level
@{ RecursionTest(level - 1); }
}
}
```
output:
```LEVEL: 3LEVEL: 2LEVEL: 1
```#### Helpers and custom members
```cs
string content = @"Hello @A, @B, @Decorator(123)";IRazorEngine razorEngine = new RazorEngine();
IRazorEngineCompiledTemplate template = razorEngine.Compile(content);string result = template.Run(instance =>
{
instance.A = 10;
instance.B = "Alex";
});Console.WriteLine(result);
```
```cs
public class CustomTemplate : RazorEngineTemplateBase
{
public int A { get; set; }
public string B { get; set; }public string Decorator(object value)
{
return "-=" + value + "=-";
}
}
```#### Referencing assemblies
Keep your templates as simple as possible, if you need to inject "unusual" assemblies most likely you are doing it wrong.
Writing `@using System.IO` in template will not reference System.IO assembly, use builder to manually reference it.```cs
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" });
```#### Credits
This package is inspired by [Simon Mourier SO post](https://stackoverflow.com/a/47756437/267736)#### Changelog
* 2024.4.1
* Expose RazorProjectEngineBuilder 🚀 #141 (thanks [@cutslikeaknife](https://github.com/ItWorksOnMyMachine))
* Documentation for RazorEngineCompilationOptionsBuilder #140 (thanks [@MichaelCleverdon](https://github.com/MichaelCleverdon))
* More asyncs #138 (thanks [@Adam Kauffman](https://github.com/A9G-Data-Droid))
* 2023.11.2
* Virtual keyword fixed
* 2023.11.1
* Template debugging 🚀 PR#111 (thanks [@shehrozeee](https://github.com/shehrozeee) and [@TheAtomicOption](https://github.com/TheAtomicOption))
* Add CancellationToken overloads to Compile methods PR#134 (thanks [@daviddotcs](https://github.com/daviddotcs))
* Package license information #133
* Code cleanup
* ⚠️ Breaking change for @Raw, [update your code from wiki](https://github.com/adoconnection/RazorEngineCore/wiki/@Raw)
* 2022.8.1
* Proper namespace handling for nested types and types without namespace #113 (thanks [@Kirmiir](https://github.com/Kirmiir))
* 2022.7.6
* Added the option to genereate pdb alongside the assembly which allows debugging the templates.
* 2022.1.2
* #94 publish as single file fix
* 2022.1.1
* Make private methods in RazorEngine protected and virtual #PR88 (thanks [@wdcossey](https://github.com/wdcossey))
* Dictionary bug in anonymous model #91 (thanks [@jddj007-hydra](https://github.com/jddj007-hydra))
* Template name fix #PR84 (thanks [@Yazwh0](https://github.com/Yazwh0))
* CI for GitHub Actions #PR69 (thanks [@304NotModified](https://github.com/304NotModified))
* Added Source Link #PR67 (thanks [@304NotModified](https://github.com/304NotModified))
* Microsoft.AspNetCore.Razor.Language 3.1.8 -> 6.0.1
* Microsoft.CodeAnalysis.CSharp 3.7.0 -> 4.0.1
* 2021.7.1
* Better error messages #PR54 (thanks [@wdcossey](https://github.com/wdcossey))
* More asyncs #PR53 (thanks [@wdcossey](https://github.com/wdcossey))
* Strong name for assembly #59 (thanks [@garryxiao](https://github.com/garryxiao))
* 2021.3.1
* fixed NET5 publish as single file (thanks [@jddj007-hydra](https://github.com/jddj007-hydra))
* AnonymousTypeWrapper array handling fix
* System.Collections referenced by default
* Microsoft.AspNetCore.Razor.Language 3.1.8 -> 5.0.3
* Microsoft.CodeAnalysis.CSharp 3.7.0 -> 3.8.0
* 2020.10.1
* Linux fix for #34
* Microsoft.AspNetCore.Razor.Language 3.1.5 -> 3.1.8
* Microsoft.CodeAnalysis.CSharp 3.6.0 -> 3.7.0
* 2020.9.1
* .NET 4.7.2 support (thanks [@krmr](https://github.com/krmr))
* 2020.6.1
* Reference assemblies by Metadata (thanks [@Merlin04](https://github.com/Merlin04))
* Expose GeneratedCode in RazorEngineCompilationException
* Microsoft.AspNetCore.Razor.Language 3.1.4 -> 3.1.5
* 2020.5.2
* IRazorEngineTemplate interface
* RazorEngineTemplateBase methods go virtual
* 2020.5.1
* Async methods (thanks [@wdcossey](https://github.com/wdcossey))
* Microsoft.AspNetCore.Razor.Language 3.1.1 -> 3.1.4
* Microsoft.CodeAnalysis.CSharp 3.4.0 -> 3.6.0
* 2020.3.3
* Model with generic type arguments compiling fix
* 2020.3.2
* External assembly referencing
* Linq included by default
* 2020.3.1
* In attribute rendering fix #4
* 2020.2.4
* Null values in model correct handling
* Null model fix
* Netstandard2 insted of netcore3.1
* 2020.2.3
* Html attribute rendering fix
* Html attribute rendering tests## Supported by
[](https://limetime.io)