让Octopress支持短链接

增加gem到Gemfile中

1
echo "gem 'dljbz'">>Gemfile

让dlj缓存不提交到git中

1
echo ".dlj-cache">>.gitignore

新增plugins/dlj_tag.rb文件,内容如下:

plugins/dlj_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
# -*- encoding : utf-8 -*-
require 'fileutils'
require 'digest/md5'
require 'dljbz'

DLJ_CACHE_DIR = File.expand_path('../../.dlj-cache', __FILE__)
FileUtils.mkdir_p(DLJ_CACHE_DIR)

module Jekyll
  class DljTag < Liquid::Tag

    def initialize(tag_name, markup, tokens)
      super
    end

    def render(context)
      output = super
      config = context.registers[:site].config
      url =config['url']
      page_url = context.environments.first["page"]["url"]
      current_url = "#{url}#{page_url}"
      if defined?(DLJ_CACHE_DIR)
        path = File.join(DLJ_CACHE_DIR, "dlj-#{Digest::MD5.hexdigest(current_url)}")
        if File.exist?(path)
          dlj_url = File.read(path)
        else
          dlj_url = Dljbz.shorten(current_url).short_url
          File.open(path, 'w') {|f| f.print(dlj_url) }
        end
      else
        dlj_url = Dljbz.shorten(current_url).short_url
      end
      dlj =  "<div class='dljbz' style='font-size:14px;'>"
      dlj += "原文地址:<a href='#{dlj_url}'>#{dlj_url}</a>"
      dlj += "</div>"
    rescue Exception => e
      puts "......dlj error: #{e.inspect}"
    end
  end

end

Liquid::Template.register_tag('dlj_tag', Jekyll::DljTag)

在source/_includes/article.html最后一行添加标签

plugins/dlj_tag.rb
1
{ % dlj_tag % }
plugins/dlj_tag.rb
1
2
bundle install
rake preview

底部就会看到

原文地址:http://dlj.bz/E4Ubjl

Comments