0
votes

I'm using a plugin to count page views for posts and pages based on Google Analytics. To display the page view count I'm using a Liquid tag {% pageview %}. Is there any way to add this data to YAML front matter, so it can be accessed in a list of popular posts on other pages by something like {{ page.views }}?

Here is the code for the Liquid tag in the plugin:

class PageViewTag < Liquid::Tag

  def initialize(name, marker, token)
    @params = Hash[*marker.split(/(?:: *)|(?:, *)/)]
    super
  end

  def render(context)
    site = context.environments.first['site']
    if !site['page-view']
      return ''
    end

    post = context.environments.first['post']
    if post == nil
      post = context.environments.first['page']
      if post == nil
        return ''
      end
    end

    pv = post['_pv']
    if pv == nil
      return ''
    end

    html = pv.to_s.reverse.gsub(/...(?=.)/,"\\&\u2009").reverse
    return html
  end #render
end # PageViewTag

How can I instead of registering a Liquid tag merge this data to the data of the post (document in a collection)? And use via {{ page.views }}.

2

2 Answers

1
votes

You can use a generator plugin to add some data['views'] to your posts or pages.

1
votes

Here is the code for the plugin I made:

require 'jekyll'

module Jekyll
  class PageviewsData < Jekyll::Generator
    safe :true
    priority :low

    def generate(site)
      # require ga-page-view plugin
      if !site.config['page-view']
        return
      end

      site.collections.each  do |label, collection|
        collection.docs.each { |doc|
          pv = doc.data['_pv']
          views = pv.to_s.reverse.gsub(/...(?=.)/,"\\&\u2009").reverse
          doc.data.merge!('views' => views)
        }
      end
    end
  end
end