简体   繁体   中英

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

您可以使用生成器插件向您的帖子或页面添加一些data['views']

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM