Categories
ASP.NET C# General

Getting started with RazorEngine

razor engine

RazorEngine is an open source templating engine based on Microsoft’s parsing engine. You can use Razor syntax to build dynamic templates. In a project that I’m working on, I’m using it to build an email based on data retrieved from different sources. Let me show you how to start using RazorEngine in your project.

Create a new console application using visual studio. Now install RazorEngine using nuget (Install-Package RazorEngine). After installing RazorEngine, you will see 2 packages in your packages.config, Microsoft.AspNet.Razor and RazorEngine.

Now create a strongly typed view.

emailTemplate

Make sure you save the file as a c# view (extension .chtml). As you can see from the above image, we are using the ConsumableData model which will hold the data for us.

With the template in place, we can add code in our Program.cs file to gather our ConsumableData by setting CustomerName to Raymond.

var data = new ConsumableData { CustomerName = “Raymond” };

With our data in place, it is time to use RazorEngine and compile our template.

var template = File.ReadAllText(“pathToTemplate”);
var email = RazorEngine.Engine.Razor.RunCompile(template, “templateKey”, typeof(ConsumableData), data, null);

After calling RazorEngine’s RunCompile method, we will have our email ready to be send.

As you can see, you can use RazorEngine to build dynamic templates. If you have used Asp.Net Mvc before, the above code should be familiar to you.

Take it for a spin and let me know what you think.