OxDEAD Unicornz

Have you ever seen so many?

(Yet Another) Octopress Image Caption Plugin

I don’t really like the default ‘img’ tag in Octopress because it doesn’t show image caption. Here are two blog posts describing how to create custom plugin which adds required functionality to Octopress.

But the problem is that image alignment does not work for variants above. (Or, probably, I just didn’t manage how to use the tag properly, lol). Anyway…

I want images with captions always centered so I’ve played with CSS and plugin definitions a bit, you can find an example below:

1
{% imgcap /images/271214_steady.JPG 400 600 Here is how it works %}

translates into

1
<div style='text-align: center;'><span class='caption-wrapper'><img src='/images/271214_steady.JPG' width='400' height='600' title='Here is how it works' ><span class='caption-text' style='width: '400'' >Here is how it works</span></span></div>

and looks like

Here is how it works

How to install

Create/modify the following files:

plugins/image_caption_tag.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Title: Image tag with caption for Jekyll
# Description: Easily output images with captions

module Jekyll

  class CaptionImageTag < Liquid::Tag
    @img = nil
    @title = nil
    @class = ''
    @width = ''
    @height = ''

    def initialize(tag_name, markup, tokens)
      if markup =~ /(\S.*\s+)?(https?:\/\/|\/)(\S+)(\s+\d+\s+\d+)?(\s+.+)?/i
        @img = $2 + $3
        if $5
          @title = $5.strip
        end
        if $4 =~ /\s*(\d+)\s+(\d+)/
          @width = $1
          @height = $2
        end
      end
      super
    end

    def render(context)
      output = super
      if @img
         "<div style='text-align: center;'>" +
           "<span class='caption-wrapper'>" +
             "<img src='#{@img}' width='#{@width}' height='#{@height}' title='#{@title}' >" +
             "<span class='caption-text' style='width: '#{@width}'' >#{@title}</span>" +
           "</span>" +
         "</div>"
      else
        "Error processing input, expected syntax: {% imgcap /url/to/image [width height] [title text] %}"
      end
    end
  end
end

Liquid::Template.register_tag('imgcap', Jekyll::CaptionImageTag)
sass/custom/_imgcaption.scss
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Image caption

@mixin reset-shadow-box() {
  @include box-shadow(0, #000, 0);
}

.caption {
  @include reset-shadow-box;
}

.caption-wrapper {
    display: inline-block;
    margin-bottom: 10px;
  .caption-text {
    background: #fff;
    text-align: center;
    font-size: .8em;
    color: #666;
    margin: 0 auto 1.5em;
    display: block;
  }
}
sass/custom/_styles.scss
1
2
3
4
// This File is imported last, and will override other styles in the cascade
// Add styles here to make changes without digging in too much

@import "custom/imgcaption"