Rendering razor templates on the fly

December 2, 2015 · 2 minute read

Dynamic content

Every now and then you need a way to generate some content using a template.

The obvious example which springs to mind is the humble email. You know, the kind you get when you register with a site, or tell them you’ve forgotten your password.

I’ve made and seen various attempts to tackle this. You can try simply looking for tokens and replacing them with content.

For example…

Dear $title$

Then write some code to find $title$ and replace it with “Mr”, “Mrs” etc.

Once you start down this path  you soon realise that you’re re-inventing a templating engine, and that’s a problem which has already been solved.

Step in Razor

So one option is to let Razor do the hard work for you.

A quick google reveals several libraries which can help, one of them is Razor Templates

Here’s an example of it’s usage…

dynamic model = new ExpandoObject();
model.Title = "Mr";
var templateContents = "Dear @Model.Title";

var compiledTemplate = RazorTemplates.Core.Template
.WithBaseType<TemplateBase>()
.Compile(templateContents);

var output = compiledTemplate.Render(model);

Compiling the template is quite an expensive operation so a bit of caching doesn’t go amiss here. In my case I just used a dictionary, base 64 encoded the template contents to use as a key and made sure to only recompile the template if the contents (key) change.

And that’s it, all the power of razor (loops, conditionals etc) is yours to use as you see fit.

When it comes to storing the templates, a NoSQL DB works nicely here.

Join the Practical ASP.NET Newsletter

Ship better Blazor apps, faster. One practical tip every Tuesday.

I respect your email privacy. Unsubscribe with one click.