Using Razor outside of MVC in .NET Core

Christof Jans picture Christof Jans · Jul 7, 2016 · Viewed 36.2k times · Source

I would like to use Razor as a templating engine in a .NET console application that I'm writing in .NET Core.

The standalone Razor engines I've come across (RazorEngine, RazorTemplates) all require full .NET. I'm looking for a solution that works with .NET Core.

Answer

Toddams picture Toddams · Jul 25, 2016

Recently I've created a library called RazorLight.

It has no redundant dependencies, like ASP.NET MVC parts and can be used in console applications. For now it only supports .NET Core (NetStandard1.6) - but that's exactly what you need.

Here is a short example:

IRazorLightEngine engine = EngineFactory.CreatePhysical("Path-to-your-views");

// Files and strong models
string resultFromFile = engine.Parse("Test.cshtml", new Model("SomeData")); 

// Strings and anonymous models
string stringResult = engine.ParseString("Hello @Model.Name", new { Name = "John" });