I'm trying to lazy load my jekyll images that feature a {{ page.path }} variable. Unfortunately the jekyll plugins available crap out when i use a path and instead work with a hardlinked image. I'm using variables in my layout to display images across multiple pages so I definitely don't want to start using hard-coded absolute paths.
Plugins are available that essentially handle the adding of lazyload class, find the w/h and renders the image with associated classes and dimensions. Below is the image-tag plugin from https://gist.github.com/ttscoff/9035690 What do I need to modify to allow a jekyll variable as a path? Or is there a better way of implementing lazyload that I'm not thinking of? For reference, my img paths are typically:
![My helpful screenshot](/images/{{ page.id }}/1.jpg)
Image tag plugin
module Jekyll
class ImageTag < Liquid::Tag
@img = {}
def initialize(tag_name, markup, tokens)
# <img class="lazy" src="img/grey.gif" data-original="img/example.jpg" width="640" height="480">
if markup =~ /(?:(\S+) )?((?:https?:\/\/|\/|\S+\/)\S+)(?:\s+(\d+))?(?:\s+(\d+))?\s+(.*)?/i
unless $2.nil?
imgclass = $1 || nil
image = $2
width = $3 || nil
height = $4 || nil
title = $5 || nil
@img = {}
@img["class"] = imgclass ? "lazy #{imgclass}" : "lazy"
begin
if image =~ /^(http:\/\/brettterpstra.com|\/)/
image.sub!(/^(http:\/\/brettterpstra.com)?/,"")
@img["data-original"] = image
filename = File.expand_path(File.join(%x{git rev-parse --show-toplevel}.strip,"source"+image))
@img["width"] = width || filename ? %x{sips -g pixelWidth "#{filename}"|awk '{print $2}'}.strip : nil
@img["height"] = height || filename ? %x{sips -g pixelHeight "#{filename}"|awk '{print $2}'}.strip : nil
else
@img["data-original"] = image
@img["width"] = width if width
@img["height"] = height if height
end
rescue
@img["data-original"] = image
@img["width"] = width if width
@img["height"] = height if height
end
@img["src"] = "/images/grey.gif"
if title && title !~ /^[\s"]*$/
if /(?:"|')(?<xtitle>[^"']+)?(?:"|')\s+(?:"|')(?<alt>[^"']+)?(?:"|')/ =~ title
@img['title'] = xtitle
@img['alt'] = alt
else
@img['alt'] = title.gsub(/(^["\s]*|["\s]*$)/, '')
end
end
end
end
super
end
def render(context)
unless @img.empty?
if context.registers[:site].config["production"]
@img["src"] = context.registers[:site].config["cdn_url"] + @img["src"]
if @img["data-original"] =~ /^(http:\/\/brettterpstra.com|\/)/
@img["data-original"] = context.registers[:site].config["cdn_url"] + @img["data-original"]
end
end
%Q{<img #{@img.collect {|k,v| "#{k}=\"#{v}\"" if v}.join(" ")}>}
else
"Error processing input, expected syntax: {% img [class name(s)] [http[s]:/]/path/to/image [width [height]] [title text | \"title text\" [\"alt text\"]] %}"
end
end
end
end
Liquid::Template.register_tag('img', Jekyll::ImageTag)