Search code examples
markdownjekylljekyll-extensionsresponsive-imageskramdown

With Jekyll 3, can I transform a post's Markdown before actual Markdown parsing?


I would like to use the Jekyll Responsive Image plugin to generate appropriate responsive images with srcset/sizes attributes for my posts' images.

But I would also like to be able to edit my posts in a software providing a live preview like MacDown, which only understands the standard Markdown syntax for images.

That's why I would like to know if there is a way —a plugin of some sort— to tell Jekyll to transform the standard Markdown syntax for images, which I would put in my Markdown files…

![alt text](path/to/image.jpg)

…into this syntax specific to the Jekyll Responsive Image plugin:

{% responsive_image path: path/to/image.jpg alt: "alt text" %}

And THEN, Jekyll could continue and use Kramdown to generate the HTML…

I also created an issue in the plugin's Github, but a more general answer would be nice too, and maybe useful for other needs.


Solution

  • Yes, this is definitely possible. Since Jekyll 3, you can have multiple converters per file extension. This allows you to create a converter like:

    class ResponsiveImageify < Jekyll::Converter
      priority :high
    
      def matches(ext)
        ext.downcase == ".md"
      end
    
      def convert(content)
        content.gsub(/\!\[(.+)\]\((.+)\)/, '{% responsive_image path: \2 alt: \1  %}')
      end
    end
    

    That converter will gsub the content of any .md file.

    Hope this helps!