Using liquid to sort posts alphabetically

后端 未结 7 1268
借酒劲吻你
借酒劲吻你 2021-02-01 19:45

Is there a way to sort a number of posts alphabetically, using Jekyll?

I have something like this now:

{% for post in site.categories.threat %}


        
7条回答
  •  遇见更好的自我
    2021-02-01 20:05

    It can be done without a plugin, which means that it works with Github Pages.

    You have to use some ugly string manipulation tricks, though.
    I used a similar approach to implement a tag page (that lists all posts for each tag).

    Same approach, slightly modified:

    {% capture posts %}
      {% for post in site.posts %}
        |{{ post.title }}#{{ post.url }}
      {% endfor %}
    {% endcapture %}
    {% assign sortedposts = posts | split: '|' | sort %}
    {% for post in sortedposts %}
        {% assign postitems = post | split: '#' %}
        {{ postitems[0] }}
    {% endfor %}

    Beware:

    You need two different separator characters inside the first loop (and of course again in the split calls later on).
    In order for this to work, both characters must not occur in any of the post titles or URLs!!

    I'm using | and # in this example, which works for me (I just tested it with my blog). But you might need to use different characters, depending on your post titles and how your URLs are constructed.


    Bonus:

    If you want to display only the posts in a certain tag/category (and not all posts), you can change the first for loop (the one inside the capture) to one of these:

    {% for post in site.tags['whatever'] %}
    
    {% for post in site.categories['whatever'] %}
    

提交回复
热议问题