Last Updated: February 25, 2016
·
1.452K
· just3ws

You can use variables in HTML emails now

Ever had to work on a particularly ugly HTML email template in Rails? I have and it's like the acronym DRY was never coined. Seriously, if you have a string of CSS being applied 10 times and are cutting and pasting the entire tag definition 10 times then you're unintentionally dooming 10 kittens to an unfortunate end

Here's a before snippet from an email template I had to update (It's in Haml)...

%tr
  %td.content-head{style: "Really? I'm not going to even replicate this CSS"}
    %h1{style: "yeah. there's a lot of CSS here"}
      And now the content
%tr
  %td.main-content-grey{style: "You get the idea. This one get's repeated a N times."}
    %p{style: "And this tag get's repeated N+1 times"}

Trying to find specific text and update the layout was annoying at best. Not a super-big deal but annoying nonetheless. This can be better though. Instead of repeating the same strings use the power of Variables to simplify your email HTML.

- content_head = "Really? I'm not going to even replicate this CSS"
- h1 = "yeah. there's a lot of CSS here"
- main_content_grey = "You get the idea. This one get's repeated a N times."
- paragraph = "And this tag get's repeated N+1 times"
%tr
  %td.content-head{style: content_head}
    %h1{style: h1}
      And now the content
%tr
  %td.main-content-grey{style: main_content_grey}
    %p{style: paragraph}

My actual case involved 7 extracted variables, one of which was a common font-family declaration that was used in each of the style definitions totally around 20 style definition string replacements. Now I was able to easily read the HTML and understand what was being used where and make global updates to styles very easily. It didn't take introducing a fancy email generation extension to simplify my email HTML generation just a little bit of Ruby and a few minutes of refactoring.