Email Templates with Handlebars

Writing email templates can be a pain, every email client comes with its own problems that can be a nightmare to fix. Some of the issues I frequently come across while building them are:

  • Fixing an issue for one email client breaks it in another
  • Just ... table layouts ... having to use markup that is not used as frequently makes the learning curve harder
  • Your styles have to be inline (can be tedious when repeating styles)

They're a lot more issues I could speak about but these are the main few that are a common problems for building emails.

My Solution

The thing I hate the most is repeating myself when it comes to writing html. So I thought to myself, "Why not use handlebars?" I built a node module that will help make it easier to build an email template. I found this useful because:

  • Table rows with the same styles and layout can be made into a partial and looped with different data.
  • Different parts of the email can be split out and reused.
  • Improves code readability

Let's Start!

If you're thinking now, "great this sounds awesome" then let's get started in getting setup.

1 . First of all you need to create your folder structure similar to this:

- data
- views
  - partials

2 . Go to HTML Snippets - Email Templates to get a basic start up template and add that to your email.hbs (optional)

3 . Run npm init and go through the setup phase. (If it isnt already setup)

4 . Run npm install handlebars-email-template --save-dev.

5 . Open up index.js and add the following code:

'use strict';

var handlebarsEmail = require('handlebars-email-template');

var options = {  
    root: './views/',
    src: 'partials/',
    dest: './compiled/',
    srcTemplate: 'email',
    destTemplate: 'email',
    ext: 'hbs',
    data: 'data/data.json'


Options explained:

  • root - templates folder
  • src - partials directory
  • dest - output html
  • srcTemplate - name of the hbs file
  • destTemplate - the name of the output file
  • ext - hbs or handlebars
  • data - template data

6 . Run node index.js.

Thats it. You should now see a new file called email.html stored within ./compiled/.

If you wish to see more information about this module you can go to the github page for more information.

Handlebars Documentation: