Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor vs. Find-and-replace for email templates

I'm seeing a lot of people using the Razor view engine for email templates. At first glance this seems like an excellent idea. However, after seeing the emails most people are generating I can't help but to wonder how using Razor is any better than simply doing a string based find and replace.

Most emails fall along the lines of something like:

<html>
<head>
    <title>Welcome to mysite.com</title>
</head>
<body>
    <p>Dear @Model.Name,</p>
    <p>An account has been created for you.</p>
    <p>Your account is FREE and allows you to perform bla bla features.</p>
    <p>To login and complete your profile, please go to:</p>
    <p><a href="@Model.LogOnUrl">@Model.LogOnUrl</a></p>
    <p>Your User ID is your email address and password is: @Model.Password</p>
</body>
</html>

In this rather trivial email why not just do something like:

string result = template.Replace("@Model.Name", Model.Name);

I suppose some further web searching could answer this question, but I haven't found a solid answer yet. Is it strictly a performance issue? Or is it just that these simple emails don't demonstrate the real advantages of using the Razor view engine?

My question here has nothing to do with how to to implement this sort of solution, I understand how to do that. My question is just is it worth the overhead of using Razor when your emails are so basic? Especially if you're using RazorEngine which takes string inputs and doesn't result in any sort of compiled class for the template.

This feels like an over engineered solution to me.

like image 854
mlindegarde Avatar asked Feb 23 '23 00:02

mlindegarde


2 Answers

Razor allows you to make more complicated emails later without needing to completely redesign your email system.

For example, you can include conditionals.

like image 132
SLaks Avatar answered Mar 05 '23 17:03

SLaks


It's a matter of performance and semantics. Sure, you CAN template emails by just using string replacement, but Razor was originally designed just for that purpose.

In your example, you're doing a lot of string replacement, which causes a bunch of strings to be created in memory. Even if you switch to StringBuilder to save on memory, you're still writing code to support your email generation.

With Razor, instead you can supply a model and keep the actual presentation layer outside of your code. Your code is involved only in gathering the details for an email, and then passing it off to another component to template. It's simpler that way for maintenance.

The RazorEngine will output a compiled class if you direct it to. In that sense, that class can be cached and invoked with incredible performance for templating.

In my opinion, it's just like the switch from WebForms to MVC; you separate your concerns and let each do their part.

like image 39
Tejs Avatar answered Mar 05 '23 18:03

Tejs