3

I'm working on a project that has both static web pages and also HTML Email templates.

As you probably know, HTML Emails require all CSS to be inlined which is a huge pain to manage. Most people use Premailer to handle this automatically - https://github.com/premailer/premailer

How would I go about using premailer with Jekyll for a certain layout?

Would it be possible to use premailer via a plugin?

Alex Phelps
  • 393
  • 4
  • 8

1 Answers1

4

Yes you can !

After you have premailer installed you can make a jekyll plugin like this one :

require 'premailer'

module Jekyll
  class Site

    # 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   = 'post'

      # this the css that will be inlined
      # this can come from site config
      @css_path = '/css/main.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 newsletters with premailer
      newsletters = [posts, pages].flatten.select{ |page_or_post|
        page_or_post.data['layout'] == @layout
      }

      newsletters.each do |newsletter|

        newsletter.output = Premailer.new(
            newsletter.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 newsletter with inlined css
        newsletter.write(dest)

      end
    end
  end
end

This is a general idea about how to integrate premailer with Jekyll. The code can certainly be improved.

Note: I've decided not to use a Generator plugin because when generators are called, sass and scss files are still not parsed and generated css is not available.

David Jacquel
  • 51,670
  • 6
  • 121
  • 147
  • I'm sorry. Could you explain how to change it for all layouts in _includes/emails/ directory? – Virkom Jan 24 '20 at 13:47