【问题标题】:Jekyll: link next/previous sorted posts within a categoryJekyll:链接一个类别中的下一个/上一个排序的帖子
【发布时间】:2020-07-31 20:46:44
【问题描述】:

我需要生成两个按钮,链接到同一类别的下一个和上一个帖子。帖子按前面的order 和一个整数值排序。

我的解决方案仍然不完美。我需要排除第一篇文章的上一个按钮和最后一篇文章的下一个按钮。但是,它不起作用,我不明白为什么。这是我的代码:

{% capture the_cat %}{{page.categories | first}}{% endcapture %}
{%- assign sorted_posts = site.categories[the_cat] | sort: 'order' -%}

{%- for post in sorted_posts -%}
  {% if post.url == page.url %}
    {% assign post_index0 = forloop.index0 %}
    {% assign post_index1 = forloop.index | plus: 1 %}
  {% endif %}
{%- endfor -%}

{%- for post in sorted_posts -%}
  {% if post_index0 == post.order %}
    {% assign prev_post = post %}
  {% endif %}
  {% if post_index1 == post.order %}
    {% assign next_post = post %}
   {% endif %}
{%- endfor -%}

最后……

{%- if prev_post != null -%} ... {%- endif -%}
{%- if next_post != null -%} ... {%- endif -%}

主循环似乎是正确的。在排序了 3 个帖子的类别中,它返回 1、2、3。我该如何解决?可以只用一个循环来修复,使代码更有效率吗?谢谢!

PD:我成功使用了这个 plugin,但是这个插件按 date 排序帖子,而不是 order

【问题讨论】:

    标签: jekyll liquid


    【解决方案1】:

    终于,我得到了解决方案:

    {%- capture the_cat -%}{{page.categories | first}}{%- endcapture -%}
    {%- assign sorted_posts = site.categories[the_cat] | sort: 'order' -%}
    
    {%- for post in sorted_posts -%}
        {%- if post.url == page.url -%}
    
        {%- assign currIndex = forloop.index0 -%}
        {%- assign prevIndex = currIndex | minus: 1 -%}
        {%- assign nextIndex = currIndex | plus: 1 -%}
        {%- assign articleIndexLength = forloop.length | minus: 1 -%}
    
        {%- if currIndex == articleIndexLength -%}
            {%- assign prev_post = sorted_posts[prevIndex] -%}
        {%- endif -%}
    
        {%- if currIndex < articleIndexLength and currIndex != 0 -%}
            {%- assign prev_post = sorted_posts[prevIndex] -%}
            {%- assign next_post = sorted_posts[nextIndex] -%}
        {%- endif -%}
    
        {%- if currIndex == 0 -%}
            {%- assign next_post = sorted_posts[nextIndex] -%}
        {%- endif -%}
    
        {%- endif -%}
    {%- endfor -%}
    

    我只需要一个带有三个条件的循环。

    【讨论】:

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