RazorLight_KirkNemeth 2.0.0
dotnet add package RazorLight_KirkNemeth --version 2.0.0
NuGet\Install-Package RazorLight_KirkNemeth -Version 2.0.0
<PackageReference Include="RazorLight_KirkNemeth" Version="2.0.0" />
paket add RazorLight_KirkNemeth --version 2.0.0
#r "nuget: RazorLight_KirkNemeth, 2.0.0"
// Install RazorLight_KirkNemeth as a Cake Addin #addin nuget:?package=RazorLight_KirkNemeth&version=2.0.0 // Install RazorLight_KirkNemeth as a Cake Tool #tool nuget:?package=RazorLight_KirkNemeth&version=2.0.0
RazorLight
Use Razor to build templates from Files / EmbeddedResources / Strings / Database or your custom source outside of ASP.NET MVC. No redundant dependenies and workarounds in pair with excellent performance and NetStandard 2.0 support
Table of contents
- Quickstart
- Template sources
- Includes (aka Partial)
- Encoding
- Additional metadata references
- Enable Intellisense support
- FAQ
Quickstart
Install the nuget package using following command:
Install-Package RazorLight -Version 2.0.0-beta1
The simplest scenario is to create a template from string. Each template must have a templateKey
that is assosiated with it, so you can render the same template next time without recompilation.
var engine = new RazorLightEngineBuilder()
.UseMemoryCachingProvider()
.Build();
string template = "Hello, @Model.Name. Welcome to RazorLight repository";
ViewModel model = new ViewModel() { Name = "John Doe" };
string result = await engine.CompileRenderAsync("templateKey", template, model);
To render a compiled template:
var cacheResult = engine.TemplateCache.RetrieveTemplate("templateKey");
if(cacheResult.Success)
{
string result = await engine.RenderTemplateAsync(cacheResult.Template.TemplatePageFactory(), model);
}
Template sources
RazorLight can resolve templates from any source, but there are a built-in providers that resolve template source from filesystem and embedded resources.
File source
When resolving a template from filesystem, templateKey - is a relative path to the root folder, that you pass to RazorLightEngineBuilder.
var engine = new RazorLightEngineBuilder()
.UseFileSystemProject("C:/RootFolder/With/YourTemplates")
.UseMemoryCachingProvider()
.Build();
string result = await engine.CompileRenderAsync("Subfolder/View.cshtml", new { Name = "John Doe" });
EmbeddedResource source
For embedded resource, key - is a namespace and key of the embedded resource relative to root Type. Then root type namespace and templateKey will be combined into YourAssembly.NamespaceOfRootType.Templates.View.cshtml
var engine = new RazorLightEngineBuilder()
.UseEmbeddedResourcesProject(typeof(Program))
.UseDefaultCachingProvider()
.Build();
Custom source
If you store your templates in database - it is recommended to create custom RazorLightProject that is responsible for gettings templates source from it. The class will be used to get template source and ViewImports. RazorLight will use it to resolve Layouts, when you specify it inside the template.
var project = new EntityFrameworkRazorProject(new AppDbContext());
var engine = new RazorLightEngineBuilder()
.UseProject(project)
.UseDefaultCachingProvider()
.Build();
// For key as a GUID
string result = await engine.CompileRenderAsync("6cc277d5-253e-48e0-8a9a-8fe3cae17e5b", new { Name = "John Doe" });
// Or integer
int templateKey = 322;
string result = await engine.CompileRenderAsync(templateKey.ToString(), new { Name = "John Doe" });
You can find a full sample here
Includes (aka Partial views)
Include feature is useful when you have reusable parts of your templates you want to share between different views. Includes are an effective way of breaking up large templates into smaller components. They can reduce duplication of template content and allow elements to be reused.
@model MyProject.TestViewModel
<div>
Hello @Model.Title
</div>
@{ await IncludeAsync("SomeView.cshtml", Model); }
First argument takes a key of the template to resolve, second argument is a model of the view (can be null)
Encoding
By the default RazorLight encodes Model values as HTML, but sometimes you want to output them as is. You can disable encoding for specific value using @Raw() function
/* With encoding (default) */
string template = "Render @Model.Tag";
string result = await engine.CompileRenderAsync("templateKey", template, new { Tag = "<html>&" });
Console.WriteLine(result); // Output: <html>&
/* Without encoding */
string template = "Render @Raw(Model.Tag)";
string result = await engine.CompileRenderAsync("templateKey", template, new { Tag = "<html>&" });
Console.WriteLine(result); // Output: <html>&
In order to disable encoding for the entire document - just set "DisableEncoding"
variable to true
@model TestViewModel
@{
DisableEncoding = true;
}
<html>
Hello @Model.Tag
</html>
Additional metadata references
When RazorLight compiles your template - it loads all the assemblies from your entry assembly and creates MetadataReference from it. This is a default strategy and it works in 99% of the time. But sometimes compilation crashes with an exception message like "Can not find assembly My.Super.Assembly2000". In order to solve this problem you can pass additional metadata references to RazorLight.
var metadataReference = MetadataReference.CreateFromFile("path-to-your-assembly")
var engine = new RazorLightEngineBuilder()
.UseDefaultCachingProvider()
.AddMetadataReferences(metadataReference)
.Build();
Enable Intellisense support
Visual Studio tooling knows nothing about RazorLight and assumes, that the view you are using - is a typical ASP.NET MVC template. In order to enable Intellisense for RazorLight templates, you should give Visual Studio a little hint about the base template class, that all your templates inherit implicitly
@using RazorLight
@inherits TemplatePage<MyModel>
<html>
Your awesome template goes here, @Model.Name
</html>
FAQ
I'm getting "Can't load metadata reference from the entry assembly" exception
Set PreserveCompilationContext to true in your *.csproj file's PropertyGroup tag.
<PropertyGroup>
...
<PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
.NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
.NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen40 was computed. tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- Microsoft.AspNetCore.Hosting.Abstractions (>= 2.1.0)
- Microsoft.AspNetCore.Html.Abstractions (>= 2.1.0)
- Microsoft.AspNetCore.Mvc.Razor.Extensions (>= 2.1.0)
- Microsoft.AspNetCore.Razor.Language (>= 2.1.0)
- Microsoft.AspNetCore.Razor.Runtime (>= 2.1.0)
- Microsoft.CodeAnalysis.Razor (>= 2.1.0)
- Microsoft.Extensions.Caching.Abstractions (>= 2.1.0)
- Microsoft.Extensions.Caching.Memory (>= 2.1.0)
- Microsoft.Extensions.DependencyInjection (>= 2.1.0)
- Microsoft.Extensions.DependencyModel (>= 2.1.0)
- Microsoft.Extensions.FileProviders.Physical (>= 2.1.0)
- Microsoft.Extensions.Primitives (>= 2.1.0)
- System.Buffers (>= 4.5.0)
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 |
---|---|---|
2.0.0 | 5,595 | 7/3/2019 |
Fork of https://github.com/toddams/RazorLight to get access to Model in Layout changes in a NuGet package