【问题标题】:Jekyll - Next and previous links with different categoriesJekyll - 不同类别的下一个和上一个链接
【发布时间】:2015-02-04 21:33:52
【问题描述】:

我正在使用 Jekyll 构建博客,我成功地在我的布局页面上实现了 Next 和 Previous 链接(使用 this answer)。我添加了几个类别(使用this answer),每个页面都会遍历正确的类别,只显示我想要的内容。

我现在唯一的问题是,Previous 和 Next 按钮仍然会遍历所有帖子,无论它们属于哪个类别。

这是我用于布局底部的 Next 和 Previous 链接的代码:

        {% if page.previous %} 
          <span class="previous-link">
            <a rel="prev" href="{{ page.previous.url }}">Previous Entry</a>
          </span>
        {% endif %}
        {% if page.next %} 
          <span class="next-link">
            <a rel="next" href="{{ page.next.url }}">Next Entry</a>
          </span>
        {% endif %}

有没有办法让“下一个”和“上一个”按钮转到当前帖子类别中的下一个或上一个帖子?

【问题讨论】:

    标签: html jekyll


    【解决方案1】:

    经过一番研究。我在这篇博文中找到了我想要的东西 - http://ajclarkson.co.uk/blog/jekyll-category-post-navigation/

    只需要在 _plugin 目录下添加一个插件,并在其中添加这段代码:

    module Jekyll
      class WithinCategoryPostNavigation < Generator
        def generate(site)
          site.categories.each_pair do |category, posts|
            posts.sort! { |a,b| b <=> a}
            posts.each do |post|
              index = posts.index post
              next_in_category = nil
              previous_in_category = nil
              if index
                if index < posts.length - 1
                  next_in_category = posts[index + 1]
                end
                if index > 0
                  previous_in_category = posts[index - 1]
                end
              end
              post.data["next_in_category"] = next_in_category unless next_in_category.nil?
              post.data["previous_in_category"] = previous_in_category unless previous_in_category.nil?
            end
          end
        end
      end
    end
    

    并且不要在 HTML 中使用 page.next.url 和 page.prev.url,只需使用 page.next_in_category.url 和 page.previous_in_category.url。

    我希望这对遇到同样问题的人有所帮助。

    【讨论】:

    • 我怎样才能在这里添加一个“排序”参数,获取帖子前端的值,比如索引、位置、重量或顺序?
    • 我在 post.data["next_in_category"] 和 post.data["previous_in_category"] 之间进行了交换,所以我有相同的 next 和 privious 行为,就像按日期排序的正常帖子
    【解决方案2】:

    如果您能够安装插件,用于类别内分页的 ajclarkson 插件是一个正确且有用的解决方案。

    如果你想部署到 Github 页面,你不能使用插件。

    我使用这种方法在类别中进行分页。这样可以确保来自不同类别的帖子永远不会出现:

    {% if page.next and page.next.categories contains "blog" %}
    
      <a href="{{ page.next.url }}">Next Post</a>
    
    {% else if page.previous and page.previous.categories contains "blog" %}
    
      <a href="{{ page.previous.url }}">Previous Post</a>
    
    {% endif %}
    

    请注意,如果必须跳过其他类别的内容,此解决方案将找不到下一篇文章。它避免了最坏的 (?) 情况,即链接到无意/并非真正发布的内容。

    【讨论】:

    猜你喜欢
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多