Sunday, 31 March 2019

RazorMachine HTML Templating Library

The other day, I needed a HTML templating library for C#. I was writing a service which sends out reports and wanted the contents to be formatted HTML. Basically, I was looking for {{ mustache }} style templates similar to JavaScript's handlebars.

As it happens there is a port of of mustache for C# called, wait for it....... Nustache! 🙂 (Gotta love that name!).

But, as with all these things the power Google led me to find out what else was out there. As it turns out there are a number of good tempting libraries for C# including:.

Microsoft Razor

I initially was settling on using DotLiquid until I remembered Microsoft's Razor Pages! They are front and center in the new ASP.NET Core world and Blazor (the experimental C# WebAssembly framework) also uses them.

The great thing about Microsoft's Razor pages is that they easily allow you to mix and layout C# model objects alongside HTML. Visual Studio gives you syntax highlighting and code completion of your C# objects and on top of all that you can add C# if and loop statements to control flow. Its a nice templating library with great IDE support. All you need to do is rename the .html file to .cshtml!

Here's a quick example of Razor syntax:

<h1>Your Action is @modelObj.ActionType </h1>
<p>Some text goes here </p>

@if (!string.IsNullOrEmpty(modelObj.Name))
{
   <p>Hello @modelObj.Name! </p>
}

<ul>
   @foreach(var favItem in modelObj.FavouriteList)
   {
     <li>@favItem.Name ( @favItem.Description )  </li>
   }
</ul>

<h3>Thats all folks!</h3>

But I didn't know if it was possible to use Razor in a simple C# console application, outside of ASP.Net. After turning back to Google, I found a plethora of libraries out there including:

The list goes on and on, but the two which looked the most promising was RazorEngine and RazorMachine. RazorEngine is the most popular however, for my purposes I went with RazorMachine because it does not produce temporary files (as RazorEngine does).

Helper Class

Using RazorMachine, I knocked up this helper class to help with reading and converting of my cshtml project files

public class RazorView
{
    private static RazorMachine m_razorMachine = null;
    public string TemplateName { get; set; }
    public object Model { get; set; }

    public RazorView(string templateName, object model)
    {
        TemplateName = templateName;
        Model = model;
        Initialise();
    }

    public static void Initialise()
    {
        if (m_razorMachine == null)
            m_razorMachine = new RazorMachine();
    }

    public string Run()
    {
        string content = null;

        if (!string.IsNullOrEmpty(TemplateName))
        {
            var htmlTemplate = ReadTemplate(TemplateName);
            content = m_razorMachine.ExecuteContent(htmlTemplate, Model).Result;
        }

        return content;
    }

    private string ReadTemplate(string fileName)
    {
        string rptTemplate = string.Format(@"{0}\Views\{1}", 
                AppDomain.CurrentDomain.BaseDirectory, fileName);

        if (!File.Exists(rptTemplate))
            return "";

        var htmlTemplate = System.IO.File.ReadAllText(rptTemplate);

        return htmlTemplate;
    }
}

With the above class we can then use it as follows:

Person modelObj = new Person();
modelObj.FirstName = "Bart";
modelObj.LastName = "Simpson";

string htmlContent = new RazorView("Test.cshtml", modelObj).Run();

Wrap Up

That's about the long and short of it. I have put a sample project on my github account here https://github.com/OceanAirdrop

free hit counter
Contact Me:  ocean.airdrop@gmail.com

Popular Posts

Recent Posts

Unordered List

Text Widget

Pages