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.

Source code, step-by-step tutorials, videos and more

I've compiled a whole load of useful tutorials, source code for articles (like this one) and mini video series to help you push through all the noise and build better ASP.NET web applications, faster.

Drop your email in the box below to get new posts first, and instant access to 'the vault'.

I respect your email privacy. Unsubscribe with one click.