Browse code

Added a plugin for easily generating <figure> and <figcaption> with images

Brandon Mathis authored on 18/07/2011 at 00:23:08
Showing 1 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,69 @@
0
+# Title: Simple Image Figure tag for Jekyll
1
+# Author: Brandon Mathis http://brandonmathis.com
2
+# Description: Easily output images in <figure> with an optional <figcaption> and class names.
3
+#
4
+# Syntax {% figure [class name(s)] url [caption text] %}
5
+#
6
+# Example:
7
+# {% figure left half http://site.com/images/ninja.png Ninja Attack! %}
8
+#
9
+# Output:
10
+# <figure class='left half'><img src="http://site.com/images/ninja.png"><figcaption>Ninja Attack!</figcaption></figure>
11
+#
12
+# Example 2 (image with caption)
13
+# {% figure /images/ninja.png Ninja Attack! %}
14
+#
15
+# Output:
16
+# <figure><img src="/images/ninja.png"><figcaption>Ninja Attack!</figcaption></figure>
17
+#
18
+# Example 3 (just an image with classes)
19
+# {% figure right /images/ninja.png %}
20
+#
21
+# Output:
22
+# <figure><img class="right" src="/images/ninja.png"></figure>
23
+#
24
+
25
+module Jekyll
26
+
27
+  class FigureImageTag < Liquid::Tag
28
+    ClassImgCaption = /(\S[\S\s]*)\s+(https?:\/\/|\/)(\S+)\s+(.+)/i
29
+    ClassImg = /(\S[\S\s]*)\s+(https?:\/\/|\/)(\S+)/i
30
+    ImgCaption = /^\s*(https?:\/\/|\/)(\S+)\s+(.+)/i
31
+    Img = /^\s*(https?:\/\/|\/)(\S+\s)/i
32
+
33
+    @img = nil
34
+    @caption = nil
35
+    @class = ''
36
+
37
+    def initialize(tag_name, markup, tokens)
38
+      if markup =~ ClassImgCaption
39
+        @class = $1
40
+        @img = $2 + $3
41
+        @caption = $4
42
+      elsif markup =~ ClassImg
43
+        @class = $1
44
+        @img = $2 + $3
45
+      elsif markup =~ ImgCaption
46
+        @img = $1 + $2
47
+        @caption = $3
48
+      elsif markup =~ Img
49
+        @img = $1 + $2
50
+      end
51
+      super
52
+    end
53
+
54
+    def render(context)
55
+      output = super
56
+      if @img
57
+        figure =  "<figure class='#{@class}'>"
58
+        figure += "<img src='#{@img}'>"
59
+        figure += "<figcaption>#{@caption}</figcaption>" if @caption
60
+        figure += "</figure>"
61
+      else
62
+        "Error processing input, expected syntax: {% figure [class name(s)] /url/to/image [caption] %}"
63
+      end
64
+    end
65
+  end
66
+end
67
+
68
+Liquid::Template.register_tag('figure', Jekyll::FigureImageTag)