带有 Jekyll 的预邮器

Premailer with Jekyll

我正在开发一个既有静态网页又有 HTML 电子邮件模板的项目。

您可能知道,HTML 电子邮件需要所有 CSS 内联,这非常难以管理。大多数人使用 Premailer 来自动处理这个问题 - https://github.com/premailer/premailer

对于特定布局,我将如何使用带有 Jekyll 的预邮程序?

是否可以通过插件使用预邮器?

是的,你可以!

安装 premailer 后,您可以制作一个像这样的 jekyll plugin :

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

这是关于如何将 premailer 与 Jekyll 集成的总体思路。 代码当然可以改进。

注意:我决定不使用 Generator plugin 因为当生成器被调用时,sass 和 scss 文件仍然没有被解析和生成 css不可用。