Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Premailer with Jekyll

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?

like image 695
Alex Phelps Avatar asked Jan 25 '26 00:01

Alex Phelps


1 Answers

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.

like image 180
David Jacquel Avatar answered Jan 27 '26 01:01

David Jacquel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!