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

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.

Build better ASP.NET web applications, faster

I email every week with hints, tips and advice on how to push through all the noise to get your ASP.NET applications built.

Drop your email in the box below and I'll send new articles straight to your inbox.

I respect your email privacy. No spam, unsubscribe anytime with one click.