花了半天总算把QRCode边栏改为了可以直接像img标签那样的用法,方便在blog中随时添加带有URL的QRCode。当然稍微修改一下还能在里面包含其他的信息,不过我目前没那种需求,所以就做这个支持了。
为了让它能像img那样的使用,因此我很干脆的直接调用了ImageTag类进行解析。
需要修改plugins/image_tag.rb:
image_tag.diff start:40 
| 1
2
3
4
5
6
7
8
9
10
11
12
13
 |     def render(context)
      if @img
        "<img #{@img.collect {|k,v| "#{k}=\"#{v}\"" if v}.join(" ")}>"
      else
        "Error processing input, expected syntax: <img class="[class name(s)]" src="[http[s]:/]/path/to/image" title="[width [height]] [title text | \"title text\" [\"alt text\"]]" alt="[width [height]] [title text | \"title text\" [\"alt text\"]]">"
      end
    end
+
+    def img_info
+      @img
+    end
  end
end
 | 
 
创建插件plugins/qrcode.rb:
qrcode.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
 | module Jekyll
  class QRCode < Liquid::Tag
    @size = ""
    @img = nil
    def initialize(tagname, markup, tokens)
        super
        if markup =~ /([^ ]+x[^ ]+ )?(.*)/i
            if !$1.nil?
                @size = $1.strip
            else
                @size = "100x100"
            end
        end
        @img = ImageTag.new('img', $2, nil)
    end
    def render(context)
        url = @img.img_info['src']
        @img.img_info['src'] = "https://api.qrserver.com/v1/create-qr-code/?size=#{@size}&margin=0&color=165B94&data=#{url.start_with?('/') ? context.registers[:site].config['url']+url : url}"
        "<a href=#{url}>#{@img.render(context)}</a>"
    end
  end
end
Liquid::Template.register_tag('qrcode', Jekyll::QRCode)
 | 
 
用法:
和img类似,就是多了一个大小的设置:
{% qrcode 150x150 http://github.com %}
效果:
