Skip to content

Instantly share code, notes, and snippets.

@jaredcwhite
Created January 21, 2021 21:20
Show Gist options
  • Save jaredcwhite/40db3cf01e66b4953c6567be449b338a to your computer and use it in GitHub Desktop.
Save jaredcwhite/40db3cf01e66b4953c6567be449b338a to your computer and use it in GitHub Desktop.
Embed PNG images as data URIs right in your Bridgetown website
# Use in Liquid or ERB templates like this:
#
# Liquid: <img src="{% datauri myimage.png %}">
# ERB: <img src="<%= datauri "myimage.png" %>">
class DatauriBuilder < SiteBuilder
def build
liquid_tag "datauri", :datauri
helper "datauri", :datauri
end
def datauri(image_path, tag=nil)
full_path = site.in_source_dir("images", image_path.strip)
data = File.read(full_path)
encoded_data = Base64.strict_encode64(data)
"data:image/png;base64,#{encoded_data}"
end
end
@jaredcwhite
Copy link
Author

jaredcwhite commented Jan 21, 2021

Just drop this in plugins/builders and you're off to the races! (If your images aren't in src/images, you can just adjust the site.in_source_dir line to pull from whatever folder you need.)

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