summaryrefslogblamecommitdiffstats
path: root/blog/_plugins/prev_next.rb
blob: 7e9c983133943fb14e1581709298c003a996e356 (plain) (tree)
























































                                                                              
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)