ZeroSharp

Robert Anderson's ones and zeros

Image Captions for Octopress

| Comments

I wanted to add captions to some of my images and came across this forum thread, from which I was able to piece together Ted Kulp’s slick solution.

The following markdown

 {% imgcap http://some.url.com/pic.jpg Leonhard Euler %} 

will render like this.

Leonhard Euler

It works with left and right too.

The changes

First, create the image_caption_tag plugin and put it in the plugins subfolder.

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
# 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
        @class = $1 || ''
        @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
        "<span class='#{('caption-wrapper ' + @class).rstrip}'>" +
          "<img class='caption' src='#{@img}' width='#{@width}' height='#{@height}' title='#{@title}'>" +
          "<span class='caption-text'>#{@title}</span>" +
        "</span>"
      else
        "Error processing input, expected syntax: {% img [class name(s)] /url/to/image [width height] [title text] %}"
      end
    end
  end
end

Liquid::Template.register_tag('imgcap', Jekyll::CaptionImageTag)

Next, modify the _utilities.scss file as follows.

sass/base/_utilities.scss
1
2
3
4
5
6
7
8
9
10
   border: $border;
 }

+@mixin reset-shadow-box() {
+  @include shadow-box(0px, 0px, 0px);
+}
+
 @mixin selection($bg, $color: inherit, $text-shadow: none){
   * {
     &::-moz-selection { background: $bg; color: $color; text-shadow: $text-shadow; }

Finally, apply the following changes to the _blog.scss file.

sass/partials/_blog.scss
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
   article {
     font-size: 2.0em; font-style: italic;
     line-height: 1.3em;
   }
-  img, video, .flash-video {
+  img, video, .flash-video, .caption-wrapper {
     @extend .flex-content;
     @extend .basic-alignment;
     @include shadow-box;
+    &.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;
+      display: block;
+    }
   }
   video, .flash-video { margin: 0 auto 1.5em; }
   video { display: block; width: 100%; }

Regenerate your Octopress site and you can start using imgcap instead of img.

Comments