bibliography.rb 1.61 KB
Newer Older
1 2 3 4 5 6 7 8 9
module Jekyll
  class Scholar

    class BibliographyTag < Liquid::Tag
  
      attr_reader :file, :config
    
      def initialize(tag_name, arguments, tokens)
        super
Sylvester Keil's avatar
Sylvester Keil committed
10

11 12 13 14 15 16 17
        @config = Scholar.defaults.dup
        @file = arguments.strip
      end

      def render(context)
        config.merge!(context.registers[:site].config['scholar'] || {})

Sylvester Keil's avatar
Sylvester Keil committed
18 19
        references = entries.map do |e|
          r = CiteProc.process e.to_citeproc, :style => config['style'],
20
            :locale => config['locale'], :format => 'html'
Sylvester Keil's avatar
Sylvester Keil committed
21 22 23 24 25 26 27 28 29 30 31 32 33
                    
          r = "<span id='#{e.key}'>#{r}</span>"
          
          if e.field?(:url)
            r << "<a href='#{e.url}'>URL</a>"
          end

          if e.field?(:doi)
            r << "<a href='#{e.doi}'>DOI</a>"
          end
          
          "<li>#{r}</li>"
        end
Sylvester Keil's avatar
Sylvester Keil committed
34

Sylvester Keil's avatar
Sylvester Keil committed
35
        "<ol>\n#{references.join("\n")}\n</ol>"
36 37 38 39 40 41 42 43 44
      end
      
      private
      
      def bibliography
        @bibliography ||= BibTeX.open(extend_path(file), :filter => :latex)
      end          
      
      def entries
Sylvester Keil's avatar
Sylvester Keil committed
45
        b = bibliography[config['query']]
46 47

        unless config['sort_by'] == 'none'
Sylvester Keil's avatar
Sylvester Keil committed
48
          b.sort_by! { |e| e[config['sort_by']].to_s }
49 50
          b.reverse! if config['order'] =~ /^(desc|reverse)/i
        end
Sylvester Keil's avatar
Sylvester Keil committed
51

52 53 54 55
        b
      end
      
      def extend_path(name)
Sylvester Keil's avatar
Sylvester Keil committed
56 57 58 59
        if name.nil? || name.empty?
          name = config['bibliography']
        end
        
60 61 62 63 64 65 66 67 68 69
        p = File.join(config['source'], name)
        p << '.bib' unless File.exists?(p)
        p
      end
    end
    
  end
end

Liquid::Template.register_tag('bibliography', Jekyll::Scholar::BibliographyTag)