2011-07-23 00:23:50 -04:00
|
|
|
# Title: Simple Image tag for Jekyll
|
2011-09-26 05:00:35 -04:00
|
|
|
# Authors: Brandon Mathis http://brandonmathis.com
|
|
|
|
# Felix Schäfer, Frederic Hemberger
|
|
|
|
# Description: Easily output images with optional class names, width, height, title and alt attributes
|
2011-07-23 00:23:50 -04:00
|
|
|
#
|
2011-09-26 05:00:35 -04:00
|
|
|
# Syntax {% img [class name(s)] [http[s]:/]/path/to/image [width [height]] [title text | "title text" ["alt text"]] %}
|
2011-07-23 00:23:50 -04:00
|
|
|
#
|
2011-09-26 05:00:35 -04:00
|
|
|
# Examples:
|
|
|
|
# {% img /images/ninja.png Ninja Attack! %}
|
|
|
|
# {% img left half http://site.com/images/ninja.png Ninja Attack! %}
|
|
|
|
# {% img left half http://site.com/images/ninja.png 150 150 "Ninja Attack!" "Ninja in attack posture" %}
|
2011-07-23 00:23:50 -04:00
|
|
|
#
|
|
|
|
# Output:
|
2011-09-26 05:00:35 -04:00
|
|
|
# <img src="/images/ninja.png">
|
|
|
|
# <img class="left half" src="http://site.com/images/ninja.png" title="Ninja Attack!" alt="Ninja Attack!">
|
|
|
|
# <img class="left half" src="http://site.com/images/ninja.png" width="150" height="150" title="Ninja Attack!" alt="Ninja in attack posture">
|
2011-07-23 00:23:50 -04:00
|
|
|
#
|
|
|
|
|
|
|
|
module Jekyll
|
|
|
|
|
|
|
|
class ImageTag < Liquid::Tag
|
|
|
|
@img = nil
|
|
|
|
|
|
|
|
def initialize(tag_name, markup, tokens)
|
2011-09-26 05:00:35 -04:00
|
|
|
attributes = ['class', 'src', 'width', 'height', 'title']
|
|
|
|
|
|
|
|
if markup =~ /(?<class>\S.*\s+)?(?<src>(?:https?:\/\/|\/|\S+\/)\S+)(?:\s+(?<width>\d+))?(?:\s+(?<height>\d+))?(?<title>\s+.+)?/i
|
|
|
|
@img = attributes.reduce({}) { |img, attr| img[attr] = $~[attr].strip if $~[attr]; img }
|
2011-09-26 05:54:45 -04:00
|
|
|
if /(?:"|')(?<title>[^"']+)?(?:"|')\s+(?:"|')(?<alt>[^"']+)?(?:"|')/ =~ @img['title']
|
|
|
|
@img['title'] = title
|
|
|
|
@img['alt'] = alt
|
2011-09-26 05:00:35 -04:00
|
|
|
else
|
2011-09-26 09:58:14 -04:00
|
|
|
@img['alt'] = @img['title'].gsub!(/"/, '"') if @img['title']
|
2011-07-29 18:29:39 -04:00
|
|
|
end
|
2011-09-26 09:58:14 -04:00
|
|
|
@img['class'].gsub!(/"/, '') if @img['class']
|
2011-07-23 00:23:50 -04:00
|
|
|
end
|
|
|
|
super
|
|
|
|
end
|
|
|
|
|
|
|
|
def render(context)
|
|
|
|
if @img
|
2011-09-26 05:00:35 -04:00
|
|
|
"<img #{@img.collect {|k,v| "#{k}=\"#{v}\"" if v}.join(" ")}>"
|
2011-07-23 00:23:50 -04:00
|
|
|
else
|
2011-09-26 05:00:35 -04:00
|
|
|
"Error processing input, expected syntax: {% img [class name(s)] [http[s]:/]/path/to/image [width [height]] [title text | \"title text\" [\"alt text\"]] %}"
|
2011-07-23 00:23:50 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
Liquid::Template.register_tag('img', Jekyll::ImageTag)
|