Surya_Vasudevan
Surya_Vasudevan

Reputation: 11

Modify img tag in post's markdown using Jekyll Hooks

I have a Jekyll blog with 1,000s of posts. Now I'm planning to use Cloudflare Image Resizing to optimize the website. To make it happen I need to modify the image tag rendered from the markdown files.

In markdown file:

![Apple](images/apple.jpg)

Rendered image tag:

<img src="images/apple.jpg" alt="Apple">

How I want it to be:

<img src="/cdn-cgi/image/width=80,quality=75/images/apple.jpg" alt="Apple" >

Thanks in advance

Upvotes: 0

Views: 185

Answers (1)

Mike Slinn
Mike Slinn

Reputation: 8403

The very last hook that gets called before writing posts to disk is :posts, :post_render. We can modify output at this hook to make edits to rendered posts and draft posts, regardless of whether they were originally written in Markdown or HTML:

module JekyllPluginHooks
  Jekyll::Hooks.register(:posts, :post_render) do |post|
    post.output.gsub!('<img src="images/', '<img src="/cdn-cgi/image/width=80,quality=75/images/')
  end
end

Terminology

  • A Jekyll post includes drafts and blog posts.
  • A Jekyll document includes web pages in all collections, including drafts and blog posts.
  • A Jekyll page is a web page that does not belong to a collection, such as posts or drafts.

For Completeness

To modify all web pages in every collection, not just drafts and posts, use the :documents hook instead of the :posts hook in the above code example:

module JekyllPluginHooks
  Jekyll::Hooks.register(:documents, :post_render) do |document|
    document.output.gsub!('<img src="images/', '<img src="/cdn-cgi/image/width=80,quality=75/images/')
  end
end

To also modify web pages that are not in a collection (for example, /index.html) also write:

module JekyllPluginHooks
  Jekyll::Hooks.register(:pages, :post_render) do |page|
    page.output.gsub!('<img src="images/', '<img src="/cdn-cgi/image/width=80,quality=75/images/')
  end
end

If we want all web pages to be modified, we can rewrite the above and extract the common code to a new method called modify_output:

module JekyllPluginHooks
  def modify_output
    Proc.new do |webpage| 
      webpage.output.gsub! \
        '<img src="images/', \
        '<img src="/cdn-cgi/image/width=80,quality=75/images/'
    end
  end

  module_function :modify_output

  Jekyll::Hooks.register(:documents, :post_render, &modify_output)
  Jekyll::Hooks.register(:pages, :post_render, &modify_output)
end

References

Upvotes: 2

Related Questions