a2bc6f97 |
# Title: Simple Image tag for Jekyll |
50eaf98c |
# 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 |
a2bc6f97 |
# |
50eaf98c |
# Syntax {% img [class name(s)] [http[s]:/]/path/to/image [width [height]] [title text | "title text" ["alt text"]] %} |
a2bc6f97 |
# |
50eaf98c |
# 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" %} |
a2bc6f97 |
#
# Output: |
50eaf98c |
# <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"> |
a2bc6f97 |
#
module Jekyll
class ImageTag < Liquid::Tag
@img = nil
def initialize(tag_name, markup, tokens) |
50eaf98c |
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 }
if @img['title'] =~ /(?:"|')([^"']+)?(?:"|')\s+(?:"|')([^"']+)?(?:"|')/
@img['title'] = $1
@img['alt'] = $2
else
@img['alt'] = @img['title'].gsub!(/"/, '') |
c837acd4 |
end |
50eaf98c |
@img['class'].gsub!(/"/, '') |
a2bc6f97 |
end
super
end
def render(context)
if @img |
50eaf98c |
"<img #{@img.collect {|k,v| "#{k}=\"#{v}\"" if v}.join(" ")}>" |
a2bc6f97 |
else |
50eaf98c |
"Error processing input, expected syntax: {% img [class name(s)] [http[s]:/]/path/to/image [width [height]] [title text | \"title text\" [\"alt text\"]] %}" |
a2bc6f97 |
end
end
end
end
Liquid::Template.register_tag('img', Jekyll::ImageTag) |