Get next and previous elements out of an array in liquid

后端 未结 5 1647
独厮守ぢ
独厮守ぢ 2021-02-03 11:48

Short version:

I want to add 1 to a number in a liquid template and use the result as an array index.

{% capture plus_one %}{{ 0 | plus: 1 }}{% endcaptur         


        
5条回答
  •  清歌不尽
    2021-02-03 12:26

    {% for category in site.categories %}
        {% assign catg_name = category.first %}
        {% if catg_name == page.category %}
            {% assign catg_posts = category.last %}
        {% endif %}
    {% endfor %}
    {% for post in catg_posts %}
        {% if post.title == page.title %}
            {% unless forloop.last %}
                {% assign next = catg_posts[forloop.index] %}
                
            {% endunless %}
            {% unless forloop.first %}
                
            {% endunless %}
        {% endif %}
        {% assign prev = post %}
    {% endfor %}
    

    As you have mentioned you can save and use the previous iteration value for the previous post link( in my case I use it as the next post link since I don't want the default newest-first order ). For the next array element you can use forloop.index. This is the 1-based index of the for loop and will give you the next item of a zero-based array.

提交回复
热议问题