A custom liquid template block tag that allows you to use the responsive image system Picturefill in Jekyll markdown files.
At the moment this template only has the option of mobile and desktop sizes. I have it hardcoded so that mobile images show up when the screen size has a max-width of 480px. You can adjust this within the function def render(context)
in the tag template and add in other options you may desire.
- Jekyll v2 http://jekyllrb.com/
- Picturefill http://scottjehl.github.io/picturefill/
You MUST specifyEdit: I had defined the markdown tag previously with the wrong processor and never noticed.markdown: kramdown
in your _config.yml even though it's supposed to be the default markdown processor. This fixed the problem of Jekyll trying to interpret the resulting html as markdown and really messing up the conditional IE9 tags.
Place this template into your _plugins
folder and name it pictureblock.rb
(or whatever name you fancy).
module Jekyll
class Picture < Liquid::Block
attr_accessor :image
def initialize(tag_name, markup, tokens)
@str = ''
@values = {}
super
end
def unknown_tag(name, params, tokens)
if name == "image"
handle_image_tag(params)
else
super
end
end
def handle_image_tag(params)
text = params.strip.gsub(/^("|')|("|')|\s$/, '')
arr = text.split(":")
key = arr.first
value = arr.last
@values[key]=value.strip
end
def render(context)
<<-MARKUP.strip
<picture>
<!--[if IE 9]><video style="display: none;"><![endif]-->
<source srcset="#{@values['mobile']}#{@values['mobile2x']?', '+@values['mobile2x']+' 2x':''}" media="(max-width: 480px)">
<source srcset="#{@values['desktop']}#{@values['desktop2x']?', '+@values['desktop2x']+' 2x':''}">
<!--[if IE 9]></video><![endif]-->
<img srcset="#{@values['desktop']}#{@values['desktop2x']?', '+@values['desktop2x']+' 2x':''}" alt="#{@values['alt']}">
</picture>
MARKUP
end
end
end
Liquid::Template.register_tag('picture', Jekyll::Picture)
{%picture%}
{%image mobile: "/my-small-image.jpg"%}
{%image mobile2x: "/[email protected]"%}
{%image desktop: "/my-medium-image.jpg"%}
{%image desktop2x: "/[email protected]"%}
{%image alt: "This is my alt tag"%}
{%endpicture%}
Note that the retina images (mobile2x or desktop2x) are optional.
<picture>
<!--[if IE 9]><video style="display: none;"><![endif]-->
<source srcset="/my-small-image.jpg, /[email protected] 2x" media="(max-width: 480px)" />
<source srcset="/my-medium-image.jpg, /[email protected]" />
<!--[if IE 9]></video><![endif]-->
<img srcset="/my-medium-image.jpg, /[email protected] 2x" alt="This is my alt tag" />
</picture>