How to get categories of a post for an Octopress plugin in class Liquid::Tag

StackOverflow https://stackoverflow.com/questions/18321455

  •  25-06-2022
  •  | 
  •  

سؤال

I have this code:

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

It outputs Array, and that's ok. But when I try some methods on categories, like size or each I get this error:

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'

I can't apply any methods on categories. Does anybody could tell me what I am doing wrong here ?

هل كانت مفيدة؟

المحلول

Happily, the fix is simple. The problem is that your code assumes every page will have an array of categories. That isn't the case for atom.xml so context.environments.first["page"]["categories"] will return nil which, of course, doesn't have the method 'size'. You can set it to only output if get_categories returns a value and you're all set.

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)

That should do it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top