Created
May 26, 2012 16:52
-
-
Save choplin/2794594 to your computer and use it in GitHub Desktop.
include image tag for jekyll(Octopress)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Title: Include Image Tag for Jekyll | |
# Authors: choplin | |
# Description: Include <img> tag with src from a specified directory | |
# Configuration: as below in your _config.yml (images/blog as default) | |
# | |
# image_dir: images/blog | |
# | |
# Syntax {% include_img [class name(s)] image_file.(jpg|jpeg|png|gif) [width [height]] [title text | "title text" ["alt text"]] %} | |
# | |
# Examples: | |
# {% include_img test.jpg %} | |
# | |
# Output: | |
# <img src="/images/blog/test.jpg"> | |
# | |
module Jekyll | |
class IncludeImageTag < Liquid::Tag | |
@img = nil | |
def initialize(tag_name, markup, tokens) | |
attributes = ['class', 'src', 'width', 'height', 'title'] | |
if markup =~ /^(?<class>\S.*\s+)?(?<src>\S+\.(?:jpg|jpeg|png|gif))(?:\s+(?<width>\d+))?(?:\s+(?<height>\d+))?(?:\s+(?<title>.+))?/i | |
@img = attributes.reduce({}) { |img, attr| img[attr] = $~[attr].strip if $~[attr]; img } | |
if /(?:"|')(?<title>[^"']+)?(?:"|')\s+(?:"|')(?<alt>[^"']+)?(?:"|')/ =~ @img['title'] | |
@img['title'] = title | |
@img['alt'] = alt | |
else | |
@img['alt'] = @img['title'].gsub!(/"/, '"') if @img['title'] | |
end | |
@img['class'].gsub!(/"/, '') if @img['class'] | |
end | |
super | |
end | |
def render(context) | |
if @img | |
image_dir = (context.registers[:site].config['image_dir'].sub(/^\//,'') || 'images/blog') | |
@img['src'] = "/#{image_dir}/#{@img['src']}" | |
"<img #{@img.collect {|k,v| "#{k}=\"#{v}\"" if v}.join(" ")}>" | |
else | |
"Error processing input, expected syntax: {% include_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('include_img', Jekyll::IncludeImageTag) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yay Ruby!!