Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

swig-email-templates

andrewrk9.6kMIT7.0.0TypeScript support: definitely-typed

Node.js module for rendering emails with swig templates and email-friendly inline CSS

readme

swig-email-templates

This package is unmaintained; please volunteer if you want it to not rely on outdated dependencies.

swig-email-templates is a Node.js module for rendering emails with Swig templates and email-friendly inline CSS using juice, inspired by niftylettuce/node-email-templates.

Features

  • Uses swig, which supports Django-inspired template inheritance.
  • Uses juice, which takes an HTML file and inlines all the <link rel="stylesheet">s and the <style>s.
  • URL rewrite support - you can provide a function to rewrite your links.
  • Text emails - for a template name passed into render(), if a file exists with the same name but a .txt extension it will be rendered separately. If the .txt file does not exist, html-to-text will auto-generate a text version of the html file. This can be disabled with the option text: false.

Upgrading from 1.x

Check out the changelog for details of what changed since 1.x. The upgrade should be pretty straightforward.

Quick start

Install:

npm install swig-email-templates

A quick working example:

var EmailTemplates = require('swig-email-templates');
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport();

var templates = new EmailTemplates();
var context = {
  meatballCount: 9001
};

const { html, text, subject } = await templates.render('meatball-sandwich.html', context) 
transporter.sendMail({
    from: 'sender@address',
    to: 'receiver@address',
    subject: subject,
    html: html,
    text: text
});

EmailTemplates API

Constructor(options)

Creates a a new EmailTemplates instance.

var EmailTemplates = require('swig-email-templates');
var templates = new EmailTemplates();

To set options, pass an object to the constructor. It can have the following keys:

root (string)

Path to template files. Defaults to path.join(__dirname, 'templates')

swig (object)

Swig options. Gets passed to swig.setDefaults(). See swig documentation for more information.

filters (object)

An object of Swig filters to set. Format: { name1: method1, name2: method2 }. For more information see Swig documentation for setFilter().

juice (object)

Juice options. See juice documentation for more information.

rewrite (function(cheerio instance))

After rendering the template and running the rewriteUrl function (see below), but before inlining resources, this function will be called if provided. It will be passed a cheerio instance and can alter its content. Cheerio instances are modified in-place so it does not need to return a value.

rewriteUrl (function (string) => string)

Each a href attribute in the output HTML will have its value replaced by the result of calling this function with the original href value.

text (boolean)

Whether to generate text alternative to HTML. Defaults to true.

Example

new EmailTemplates({
  root: '/var/www/test.site/templates',
  text: false,       // Disable text alternatives
  swig: {
    cache: false     // Don't cache swig templates
  },
  filters: {
    upper: function(str) {
      return str.toUpperCase();
    }
  },
  juice: {
    webResources: {
      images: 8      // Inline images under 8kB
    }
  },
  rewriteUrl: function (url) {
    return url + 'appendage';
  },
  rewrite: function($) {
    $("img").each(function(idx, anchor) {
      $(anchor).attr('src', 'no-img.png');
    });
  }
})

render(templateName, context, callback?)

Render a template with templateName, with the context provided.

If no callback is given, returns a promise which resolves to an object that looks like { html, text, subject }.

If a callback function is given, use legacy callback style. The callback has the signature function(err, html, text, subject).

Example (promise):

const EmailTemplates = require('swig-email-templates');
const templates = new EmailTemplates();
const { html, text, subject } = await templates.render('template.html', { user: 55 })
// html is inlined html
// text is text equivalent
// subject is parsed subject template or null if not found

Example (callback):

const EmailTemplates = require('swig-email-templates');
const templates = new EmailTemplates();
templates.render('template.html', { user: 55 }, function (err, html, text, subject) {
  // html is inlined html
  // text is text equivalent
  // subject is parsed subject template or null if not found
})

Behaviour of text templates

If the 'text' option is true (see above), then swig-email-templates will attempt to create a text equivalent as well as your HTML. By default, this will be by rendering the HTML output as text using html-to-text.

You can provide your own text template to override this behaviour. This should have the same basename as your HTML template but end in '.txt' instead of '.html'. For example, if your HTML template is 'template.html' then the text version should be 'template.txt'. This will receive the same context as the HTML template.

If the 'text' option is false, then no text alternative will be generated and the callback passed to the EmailTemplate.render() function will receive a falsy value instead of text as its third argument.

Behaviour of subject templates

swig-email-templates will attempt to create a text equivalent as well as your HTML. This template should have the same basename as your HTML template but end in .subject.txt. This will receive the same context as the HTML template.

Using subject templates, you can generate subject that contains variables.

Command Line

Installing swig-email-templates through npm will put the swig-email-templates command in your system path, allowing it to be run from any directory.

Usage

swig-email-templates [files] [options]

Where [files] can be any number of input files to process.

The options are:

  • -v, --version: Display the installed version of swig-email-templates
  • -h, --help: Show the help screen
  • -o, --output: The directory to output your files to. Defaults to stdout
  • -r, --root: The root location for the files. The default is ..
  • -j, --json: The file that contains your context, stored in JSON.
  • -c, --context: The file that contains your context, stored as a CommonJS module. Used only if -j is not provided.

Example

The following example renders two files, email1.html and email2.html, which are both contained in the cwd. It uses the context stored in context/main.json for rendering, and places the results in the folder output.

swig-email-templates email1.html email2.html -o output/ -j context/main.json

Tests

npm test

changelog

7.0.0

  • Provide async version of main render method
  • Depend on yargs rather than minimist, removing dependency on an unmaintained package
  • Upgrade dependencies: html-to-text 6 -> 8, juice 7 -> 8
  • Support only Node 14, 16, 18
  • Internal refactoring to a more modern code style

6.0.0

  • Upgrade dependencies: juice 4.1.0 -> 7.0.0, swig-templates 2.0.2 -> 2.0.3, html-to-text 3.3.0 -> 6.0.0
  • Check in package lockfile

4.0.0

  • Warning: swig is no longer maintained. Use this package at your own risk. You may wish to switch to nunjucks and for emails, use email-templates.
  • Upgrade to Juice 3. This brings changes from its dependency web-resource-inliner.
  • Add support for email subject.

3.0.0

  • Upgrade to Juice 2. This changes various defaults for inlining styles. See the list of changes in Juice for more information. These are mostly changes around preserving @font-face and @media, and applying widths/heights to tables.
  • Fix Outlook-breaking cheerio config (issue #34)
  • Update README for command-line utility

2.1.0

  • Add new option: 'rewrite'
    • This allows you to read and alter the rendered HTML in whatever way wish before inling resources or generating text alternatives
  • Update dependencies

2.0.0

  • Support for Node 4+ as well as 0.10 & 0.12
  • Switch to Cheerio instead of JSDom for compatibility with a wider range of Node versions
    • this means that the HTML you provide in your template will be closer to the output of swig-email-templates. JSDom added in html, body, tbody tags where Cheerio doesn't
  • Switch back to the the original 'juice' which is now more actively maintained
    • this version of juice also inlines images using data: URLs
    • be mindful that juice will fetch external resources for inlining, which can take some time
  • At the same time it made sense to refactor the API a bit:
    • the library presents itself as a class with a constructor method
    • rewriteUrl is now an option on EmailTemplates instead of an extra argument to render()
    • commandline tool no longer takes 'render' as a parameter
  • Add support for setting filters on the swig instance
  • Much more comprehensive documentation

1.4.0

  • Marcin Jekot and domasx2
    • update to work on node v0.12 and fix test failures.

1.3.0

  • Connor Keenan
    • support text templates as well as html, and automatically render text emails based on the html when none is provided.

1.2.0

  • Andrew Kelley
    • pend instead of batch dev dependency
    • update dependencies
    • extract CHANGELOG from README
    • add Expat license

1.1.0

  • Dennis
    • Allow options to be passed to juice

1.0.1

  • Joshua Halickman
    • Pass options to swig if we want to set any outside of the swig-email-templates
    • Update package.json

1.0.0

  • BREAKING CHANGE - the ability to generate a dummy context was removed because swig dropped support for ability to access the parse tree when it went to 1.x.
  • Update swig dependency to 1.3.0
  • Update jsdom dependency to 0.8.11
  • Switch to juice2 fork

0.7.0

  • added command line program (thanks jmeas)

0.6.0

  • updated swig to 0.14.0

0.5.1

  • updated juice to 0.4.0

0.5.0

  • BREAKING CHANGE - render and generateDummy no longer automatically append .html to your template name to look it up. This means that if you before had render('meatball-sandwich') you must change it to render('meatball-sandwich.html') to work with 0.5.0.
  • fixed crash during cleanup
  • updated juice to 0.3.2
  • updated jsdom to 0.5.4