如何在Jekyll中按帖子数对site.tags进行排序? [英] How do you sort site.tags by post count in Jekyll?

查看:42
本文介绍了如何在Jekyll中按帖子数对site.tags进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,我是Ruby的新手,但是我试图在模板中添加一个液体标记,以便可以循环显示五个最受欢迎的标记的列表.

Apologies as I'm new to Ruby, but I'm trying to add a liquid tag to my template that I can loop over to show a list of the five most popular tags.

由于某种原因,当我使用该插件时,它只会输出一个标签.

For some reason this plugin just outputs a single tag when I use it.

这是我在mu插件中放的内容:

Here is what I put in mu plugin:

module Jekyll
  class PopularTags < Liquid::Tag

    def initialize(tag_name, text, tokens)
      super
    end

    def render(context)
      tags = context.registers[:site].tags
      return tags.sort_by { |tag, posts| posts.count }
    end
  end
end
Liquid::Template.register_tag('popular_tags', Jekyll::PopularTags)

这是我放在模板中的内容:

Here is what I put in my template:

{% popular_tags %}

推荐答案

实际上,根据我目前正在阅读的内容,Jekyll中的Tag插件应像标签一样使用,而不应像变量一样使用.因此,在那种情况下,您确实应该在模板中使用它:

Well actually, from what I'm currently reading, the Tag plugins in Jekyll should be used just like a tag and not like a variable. So in that case, you should indeed use this in your template :

{% popular_tags %}

但这是您的班级的行为似乎是错误的.它不应返回变量/哈希,而应返回将代替popular_tags标签显示的HTML代码.

But it's the behaviour of your class that seems to be wrong. It should not return a variable/hash, it should return the HTML code that will be displayed in stead of the popular_tags tag.

例如,您可以执行以下操作:

For instance, here's something you could be doing :

module Jekyll
  class PopularTags < Liquid::Tag

    def initialize(tag_name, text, tokens)
      super
    end

    def render(context)
      tags = context.registers[:site].tags

      html = "<ul>"
      sorted = tags.sort_by { |t,posts| posts.count }
      sorted.each do |t, posts|
        html << "<li>TAG: #{t} (#{posts.count})</li>"
      end
      html << "</ul>"

      html
    end
  end
end

Liquid::Template.register_tag('popular_tags', Jekyll::PopularTags)

希望这会有所帮助.我刚试过,它按预期工作.如果要首先显示最常用的标签,只需更改sort_by行,并使用-posts.count而不是posts.count.

Hope this helps. I just tried it and it's working as intended. If you want to display the most used tags first, just change the sort_by line, and use -posts.count instead of posts.count.

您可以查看其他插件源代码,可能会对您有所帮助.

You can have a look at this other plugin source code, might help you.

这篇关于如何在Jekyll中按帖子数对site.tags进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆