Document templates in .NET

Jonathan Harrison
2 min readOct 16, 2017

--

Recently I have been working on a project where we needed a Template Engine such that we could easily generate PDFs and emails from templates.

After doing some research on options in the .NET universe, I found these libraries:

After looking into each of them, I went with DotLiquid. the reasons were that Liquid was created by Shopify for the exact requirements we had and also, it is used by a large number of companies including some big names such as GoDaddy, Rackspace and Zendesk. Furthermore, RazorEngine seems to generate temporary files according to the documentation and I didn’t like the idea of having to perform clean up; whilst RazorLight does look promising but a bit too early to use yet, maybe worth revisiting when 2.0 is released.

DotLiquid is simply a .NET port of the Ruby liquid engine, to demonstrate its simplicity I created an example project on my GitHub.

Create a template

First of all, create an instance of the Template class by parsing a Liquid string with:

Template template = Template.Parse(liquidTemplateString);

The Template instance could be cached to save re-parsing the template every time it is used.

Create a hash

Next is to create a hash of your model object; your Model object could be an anoymous object, a class inheriting from Drop or a POCO (See the DotLiquid documentation for more details). This is done with:

Hash hash = Hash.FromAnonymousObject(new { Model = data });

Combine the hash and the template

Finally, call the Render method on the Template instance created earlier passing the hash:

string renderedOutput = template.Render(hash);

That’s it! Your template will be rendered with the data you passed in.

My example GitHub project contains a Console App combining all this and also, shows some of the DotLiquid’s configuration options such as date formats and naming conventions.

By the way if you use Visual Studio Code, there are two useful Liquid extensions:

--

--

Jonathan Harrison
Jonathan Harrison

Written by Jonathan Harrison

Principal Software Engineer @ Tripadvisor. Formerly at Spotify, Altitude Angel and Microsoft. All opinions are my own.

Responses (1)