Search code examples
htmlconditional-statementsjekyllliquidalphabetical

Jekyll: Sorting pages alphabetically by the title hash, replaced by another hash only if it exists


My YAML always has a title hash for pages.

---
title: Why Green and Black Teas Should be Mixed.
---

The YAML sometimes has a title-override hash for some pages.

---
title: Why Green and Black Teas Should be Mixed.
title-override: Best reasons why Green and Black Teas Should be Mixed.
---

This title-override hash is so I can change the wording in an archive.

The archive has conditional logic to only use the title hash if there's no title-override hash. It looks like this:

<table>
  <tbody>
    {% assign sorted_by_title = site.pages | sort:'title' %}
    {% for page in sorted_by_title %} 
      <tr>
        <td>
          <a href="{{ site.url }}{{ page.url }}">
            {% if page.title-override %}
              {{ page.title-override }}
            {% else page.title %}
              {{ page.title }}
            {% endif %}
          </a>
        </td>
      </tr>
    {% endfor %}
  </tbody>
</table>

The problem: I'm sorting by title alphabetically. "Why" comes after "Bad" and "Friendly", so the table order would go something like:

  1. Bad Dogs Always Go To Doggie Heaven?
  2. Friendly Potato Farming Tips.
  3. Best reasons why Green and Black Teas Should be Mixed.
  4. YouTube Censors Unicorn Videos Because of Rainbow Blood.

What appears unfortunately isn't alphabetical because I'm sorting by title, not what appears.

And if I sort by title-override, "Best reasons why Green and Black Teas Should be Mixed." unfortunately appears first, if it's the only one with the title-override hash.

How do I sort by what appears, instead of only by title or title-override? I've tried using group_by and group_by_exp to sort by both but it didn't work.


Solution

  • Change in your line pages to posts

    {% assign sorted_by_title = site.pages | sort:'title' %} to {% assign sorted_by_title = site.posts | sort:'title' %}

    and create the related _post folder.

    In case of sorting, check LOWERCASE and UPPERCASE in your title