summaryrefslogtreecommitdiffstats
path: root/blog/_plugins/prev_next.rb
blob: 7e9c983133943fb14e1581709298c003a996e356 (plain) (blame)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
require 'pry-byebug'

module Jekyll
  class PrevNextTag < Liquid::Tag

    def initialize(tag_name, text, tokens)
      super
      @tag = tag_name
      @text = text
    end

    def render(context)
      page = context['page']
      other_page = case @tag
      when "link_to_prev_page" then find_prev(page)
      when "link_to_next_page" then find_next(page)
      else nil
      end

      if other_page
        %Q{<a href="#{other_page['url']}">#{@text} #{other_page['title']}</a>}
      else
        ""
      end
    end

    private

    def find_prev(obj)
      n = obj.previous
      loop do
        if n && n['lang'] != obj['lang']
          n = n.previous
        else
          break
        end
      end
      return n
    end

    def find_next(obj)
      n = obj.next
      loop do
        if n && n['lang'] != obj['lang']
          n = n.next
        else
          break
        end
      end
      return n
    end

  end
end

Liquid::Template.register_tag('link_to_next_page', Jekyll::PrevNextTag)
Liquid::Template.register_tag('link_to_prev_page', Jekyll::PrevNextTag)