【问题标题】:How to get categories of a post for an Octopress plugin in class Liquid::Tag如何在 Liquid::Tag 类中获取 Octopress 插件的帖子类别
【发布时间】:2013-08-19 19:20:37
【问题描述】:

我有这个代码:

module Jekyll
  class ConnexeTag < Liquid::Tag
    def render(context)
      categories = get_categories(context)
      categories.class.name # => "Array"
      # categories # => "category1category2"
      # categories.join(',') # => Error !
      # categories.size # => Error !
    end

    private

    def get_categories(context)
      context.environments.first["page"]["categories"]
    end
  end
end

它输出数组,没关系。但是当我在categories 上尝试一些方法时,比如sizeeach我收到这个错误:

Building site: source -> public
Liquid Exception: undefined method `size' for nil:NilClass in atom.xml
/home/xavier/octopress/plugins/connexe_tag.rb:25:in `render'

我无法在categories 上应用任何方法。 有人能告诉我我在这里做错了什么吗?

【问题讨论】:

    标签: liquid octopress


    【解决方案1】:

    幸运的是,修复很简单。问题是您的代码假定每个页面都有一个类别数组。 atom.xml 不是这种情况,所以context.environments.first["page"]["categories"] 将返回nil,当然,它没有“size”方法。您可以将其设置为仅在 get_categories 返回一个值并且一切就绪时才输出。

    module Jekyll
      class ConnexeTag < Liquid::Tag
        def render(context)
          categories = get_categories(context)
    
          # return a list of categories for pages which have them
          categories.join(', ') if categories
        end
    
        private
    
        def get_categories(context)
          context.environments.first["page"]["categories"]
        end
      end
    end
    
    
    Liquid::Template.register_tag('connexe_tag', Jekyll::ConnexeTag)
    

    应该可以的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多