Search code examples
yamljekyllliquidjekyll-extensions

How to add a Liquid tag into YAML front matter in Jekyll?


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 }}.


Solution

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