3
votes

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.

3

3 Answers

5
votes

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!

2
votes

Simplest solution is to use new Jekyll hooks

A very raw plugin can be :

Jekyll::Hooks.register :posts, :pre_render do |post, payload|
  docExt = post.extname.tr('.', '')
  # only process if we deal with a markdown file
  if payload['site']['markdown_ext'].include? docExt
    newContent = post.content.gsub(/\!\[(.+)\]\((.+)\)/, '{% responsive_image path: \2 alt: \1  %}')
    post.content = newContent
  end
end

Store this in _plugins/img-tag-transform.rb

0
votes

The examples posted here break the alt tag. The alt string needs to be quoted otherwise it gets truncated into one word.

e.g. content.gsub(/\!\[(.+)\]\((.+)\)/, '{% responsive_image path: \2 alt: "\1" %}')

Also Nicolas Hoizey's post is the only one that works for me on the latest version of Jekyll (3.7), I can't seem to make the other examples output html. Markdown appears to have been rendered before this inserts the liquid tags.