Inlining CSS on HTML Emails is a pain point for anyone, it’s just hard, easy to miss things, hard to maintain, and just tiresome. There are some great tools out there that help do this for you, like this CSS Inliner Tool.
If you dig a little deeper, you’ll probably find a library called Premailer which does the same thing but allows you to install it on your own server and integrate it into your workflow.
For static pages, I’m using Gh-pages, hosted free by github and also using Jekyll templates to automatically generate my files – really great tool for maintaining a static site.
So, how does someone use static pages on gh-pages and Premailer together to maintain some HTML email templates?
All of these instructions you’ve already installed and are using Jekyll, learn more.
Step 1 – gem install premailer
Step 2 – Create a new directory called _plugins
inside your repo
Step 3 – Use the Gist below to create a new plugin for Premailer
require 'premailer' | |
module Jekyll | |
class Site | |
#declare plugin properties | |
#safe true | |
#priority :low | |
# create an alias for the overriden site::write method | |
alias orig_write write | |
# we override the site::write method | |
def write | |
# first call the overriden write method, | |
# in order to be sure to find generated css | |
orig_write | |
# layout name we are looking for in pages/post front matter | |
# this can come from site config | |
@layout = 'email-base' | |
# this the css that will be inlined | |
# this can come from site config | |
@css_path = 'assets/css/email.css' | |
# look for generated css file content | |
@cssPages = pages.select{ |page| | |
page.destination(dest).include? @css_path | |
} | |
# look again in pages and posts | |
# to generate inlinedcontent with premailer | |
inlinedcontent = [posts, pages].flatten.select{ |page_or_post| | |
page_or_post.data['layout'] == @layout | |
} | |
inlinedcontent.each do |inlinedcontent| | |
inlinedcontent.output = Premailer.new( | |
inlinedcontent.output, | |
{ | |
# declare that we pass page html as a string not an url | |
:with_html_string => true, | |
# also pass css content as a string | |
:css_string => @cssPages.join, | |
} | |
).to_inline_css; | |
# rewrite the content with inlined css | |
inlinedcontent.write(dest) | |
end | |
end | |
end | |
end |
Step 4 – Config premailer.rb
. You’ll want to rename the layout and CSS file name to the one you’re project has.
That’s it! Right now Jekyll Plugins can’t be used on Gh-pages but you can copy the generated files from your local to your email tool or app that you’re working on. With some cleanup we might even be able to get this plugin supported on Gh-pages.
html emails inline css jekyll premailer