Skip to content

Instantly share code, notes, and snippets.

@YJPL
Last active October 14, 2022 17:03
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YJPL/48718e28d2b2fda3476aceac018c8f26 to your computer and use it in GitHub Desktop.
Save YJPL/48718e28d2b2fda3476aceac018c8f26 to your computer and use it in GitHub Desktop.
Jekyll plugin to replace Markdown images e.g. `![alt description](image.jpg)` with `{% picture %}`. This tag works for collections in addition to posts. Written to work combined with Jekyll Picture Tag. The link opens the original image.
# Description: Jekyll plugin to replace Markdown image syntax with HTML markup, written to work combined with Jekyll Picture Tag
Jekyll::Hooks.register :documents, :pre_render do |document, payload|
docExt = document.extname.tr('.', '')
# only process if we deal with a markdown file
if payload['site']['markdown_ext'].include? docExt
newContent = document.content.gsub(/!\[(.*)\]\(([^\)]+)\)(?:{:([^}]+)})*/, '{% picture default \2 --alt \1 --link /img/\2 %}')
document.content = newContent
end
end
@YJPL
Copy link
Author

YJPL commented Oct 14, 2022

Improved thanks to https://gist.github.com/tadamcz/869802c919c72172486f219751904108

Jekyll::Hooks.register :documents, :pre_render do |document, payload|
  file_ext = document.extname.tr('.', '')

  # This regex will match all of the following correctly:
  #
  # ![](image.png)
  # ![Alt text](image.png)
  # ![Alt text!'"@#$%^&*](image.png)
  # [![Alt Text](image.png)](https://example.com)
  # > [![Alt Text](image.png)](https://example.com)
  image_markdown = /!\[([^()]*)\]\(([^()]+)\)/

  # Only process if we deal with a markdown file
  if payload['site']['markdown_ext'].include? file_ext

    document.content = document.content.gsub(image_markdown) do
      match = Regexp.last_match
      alt_text = match[1]
      src = match[2]

      # If alt text is empty, try to infer it from the file name
      # Results may not always be desirable
      if alt_text == "" and src
        alt_text = File.basename(src, File.extname(src))
        alt_text = alt_text.gsub(/[_\-]/, " ").gsub("/", "")
      end

      "{% picture default #{src} alt=\"#{alt_text}\" %}"
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment