• Stars
    star
    336
  • Rank 125,564 (Top 3 %)
  • Language
    HTML
  • License
    MIT License
  • Created over 4 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Razor Templating Engine to render Razor Views(.cshtml files) to String in Console, Web, Service, Desktop workloads in .NET Core 3+

Razor.Templating.Core

Build+Test Nuget Downloads Coverage

Using Razor for HTML templating was never been so easy like this. Render your .cshtml files into string easily using this library.

This project makes use of Razor SDK for precompiling the views.

Supported Application Types

.NET Core 3.0 .NET Core 3.1 .NET 5 > .NET 6
Preferred Version v1.6.0 v1.6.0 v1.6.0 1.9.0-rc.2
Console โœ“ โœ“ โœ“ โœ“
Api โœ“ โœ“ โœ“ โœ“
Mvc โœ“ โœ“ โœ“ โœ“
Worker Service โœ“ โœ“ โœ“ โœ“
WPF โœ“ โœ“ โœ“ โœ“
WinForms โœ“ โœ“ โœ“ โœ“
Azure Functions โœ“ โœ“ โœ“ โœ“

Supported View Features

MVC Razor View Features
ViewModel โœ“
ViewBag โœ“
ViewData โœ“
Layouts โœ“
ViewStarts โœ“
ViewImports โœ“
Partial Views โœ“
Tag Helpers โœ“
View Components (.NET 5 +) โœ“
Dependency Injection into Views โœ“
@Url.ContentUrl** โœ—
@Url.RouteUrl** โœ—

**Contributors are welcome who can help to enable these unsupported features.

Applications

  • Email Templating
  • Report Generation & more

Installing Nuget Package

This library is available as Nuget package

Using .NET CLI
dotnet add package Razor.Templating.Core
Using Package Reference .csproj
<PackageReference Include="Razor.Templating.Core" Version="1.9.0-rc.2" />

Simple Usage:

using Razor.Templating.Core;

var model = new ExampleModel()
{
    PlainText = "This text is rendered from Razor Views using Razor.Templating.Core",
    HtmlContent = "<em>You can use it to generate email content, report generation and so on</em>"
};

// Both ViewBag and ViewData should be added to the same dictionary. 
var viewDataOrViewBag = new Dictionary<string, object>();
// ViewData is same as mvc
viewDataOrViewBag["Value1"] = "1";

// ViewBag.Value2 can be written as below. There's no change on how it's accessed in .cshtml file
viewDataOrViewBag["Value2"] = "2";

var html = await RazorTemplateEngine.RenderAsync("/Views/ExampleView.cshtml", model, viewDataOrViewBag);

Before applying this code, follow this article for sample implementation: https://medium.com/@soundaranbu/render-razor-view-cshtml-to-string-in-net-core-7d125f32c79

Render View Without Layout

In case if there's a need to render a view without layout, use RenderParitalAsync() method.

var html = await RazorTemplateEngine.RenderPartialAsync("/Views/ExampleView.cshtml", model, viewDataOrViewBag);

Razor Views in Library

Razor view files(.cshtml) can be organized in a separate shared Razor Class Libary(RCL). Sample library can be found here

The Razor Class Library's .csproj file should look something like below. Whereas, AddRazorSupportForMvc property is important.

Also, RCL should be referenced to the main project or where the RazorTemplateEngine.RenderAsync method is invoked.

<Project Sdk="Microsoft.NET.Sdk.Razor">
  <PropertyGroup>
    <TargetFrameworks>net6.0</TargetFrameworks>
    <AddRazorSupportForMvc>true</AddRazorSupportForMvc>
  </PropertyGroup>

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>
</Project>

Dependency Injection

Dependencies can be injected directly into views using @inject in .csthml file. Refer sample application here

In ASP.NET Core, add dependency like below in Startup.cs -> ConfigureServices

...
services.AddTransient<ExampleService>();
//add after registering all the dependencies
services.AddRazorTemplating();

or in console or other applications, add as below

using Microsoft.Extensions.DependencyInjection;

// Add dependencies to the service collection
var services = new ServiceCollection();
services.AddTransient<ExampleService>();
// Add RazorTemplating after registering all dependencies
// this is important for the razor template engine to find the injected services
services.AddRazorTemplating(); 

Once the dependencies are registered, we can use either one of these ways:

Using RazorTemplateEngine static class

var html = await RazorTemplateEngine.RenderAsync("~/Views/ExampleViewServiceInjection.cshtml");

Using IRazorTemplateEngine

  • Instead of using the RazorTemplateEngine static class, it's also possible to use the IRazorTemplateEngine interface to inject dependency directly into the constructor.
public class MyService {
    private readonly IRazorTemplateEngine _razorTemplateEngine;

    public MyService (IRazorTemplateEngine razorTemplateEngine)
    {
        _razorTemplateEngine = razorTemplateEngine;
    }

    public async Task Index()
    {
        var renderedView = await _razorTemplateEngine.RenderAsync("/Views/Home/Index.cshtml");
        // do something with renderedView
    }
}

How to render razor views from absolute path

We can make use of ASP.NET Core's inbuilt RazorRuntimeCompilation to render any .cshtml inside or outside of the project.

As of v1.7.0+, we can achieve this as below:

using Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Razor.Templating.Core;

var services = new ServiceCollection();
services.AddMvcCore().AddRazorRuntimeCompilation();
services.Configure<MvcRazorRuntimeCompilationOptions>(opts =>
{
    opts.FileProviders.Add(new PhysicalFileProvider(@"D:\PathToRazorViews")); // This will be the root path
});
services.AddRazorTemplating();

var html = await RazorTemplateEngine.RenderAsync("/Views/Home/Rcl.cshtml"); // relative path to the root

Please note this may become slightly better in the future versions of our library.

Note:

  • Please ensure that the views path is always unique among all the shared template projects.

Sample Applications

Please find the sample applications here

Support

If you find this helpful, consider supporting the development of this library by sponsoring one or more coffeeย ;) Thanks!

References:

Thanks to all the great articles and projects which helped to bring this library out!