Pages

Tuesday, February 4, 2014

Quick and Compliant Email Templates using Razor

Even in today's hyper connected world where you can Tweet someone's TV or Instagram your refrigerator, it seems like when it comes to business, Email is still king. If you need a simple, effective, and fast way to create a templated email in code, I suggest using Razor as your templating engine.

If you've done any MVC development since version 3, you've likely used the new Razor View Engine. Its concise and semantic, and it gets out of the way of your html. Best of all, it's not dependent on MVC, so you can re-purpose it in many different ways.

There are already a few existing projects that surround Razor templates. In this example I'm using the following project, but you can use whatever you prefer to get the job done:

https://github.com/volkovku/RazorTemplates

I like the RazorTemplates project because like Razor itself, the syntax in the RazorTemplates project is concise and semantic.

We're going to need an email template as well, so I suggest using the following boiler plate template:

One thing to note with this template. It contains a few "@" characters that will need to be escaped in order to work with the Razor engine. Fix this by adding an additional "@" symbol, resulting in a double "@@".

Add the RazorTemplates assembly to your project using NuGet.
PM> Install-Package RazorTemplates

With just a few lines of code we can load up our template file, compile it, and then render it.

string templateFile = File.ReadAllText("/Templates/EmailTemplate.html");
var template = Template.Compile(templateFile);
string emailBody = template.Render(new { Name = "Everett" });

To render data in our template file, we can use the Razor engine's Model syntax to access the object data that we have passed into the template.Render() method. In this case we can access the "Name" property on our object by adding the following line to out template file:

<body>
    Thanks for visiting our site @Model.Name
</body>

And that's it! No more string.Replace(), no more XSLT, no more wasted time creating mail templates!

1 comment:

  1. Great tips! It should work well for me, because i am tired to download templates for each new kind of letter from http://www.nl.poweredtemplate.com/brochure-templates/newsletters/free/index.html and then edit it for my needs.

    ReplyDelete