Skip to content

Workaround for sorting pages by data values

Mikk Pristavka edited this page Jun 22, 2017 · 2 revisions
{% comment %}sorting subpages by their data attributes {% endcomment %}

{% assign sort_array_str = "" %}
{% for subpage in page.visible_children_with_data %}
  {% comment %} append "," {% endcomment %}
  {% if sort_array_str != "" %}{% assign sort_array_str = sort_array_str | append: "," %}{% endif %}

  {% comment %}every element is a string in the format <DATA.DATE>|<PAGE ID>{% endcomment %}
  {% assign sort_array_str = sort_array_str | append: subpage.data.date | append: "|" | append: subpage.page_id %}
{% endfor %}

{% comment %}Split by "," to get each element, sort and reverse the resulting array{% endcomment %}
{% assign sort_array = sort_array_str | split: "," | sort | reverse %}

{% comment %}Render only 5 first pages{% endcomment %}
{% assign count = 5 %}
{% for s in sort_array_arr %}

  {% comment %}Split the array element to separate the page.id from the data.date value{% endcomment %}
  {% assign s_arr = s | split: "|" %}

  {% comment %}Convert the string to a number{% endcomment %}
  {% assign s_page_id = s_arr.last | to_num %}

  {% comment %}Loop through the subpages a second time{% endcomment %}
  {% for subpage in item.visible_children_with_data %}
    {% comment %}Render only the page that has the same ID as s_page_id{% endcomment %}
    {% if s_page_id == subpage.page_id %}

      {% comment %}Render the "subpage" component and provide the specific page as a component variable{% endcomment %}
      {% include "subpage" page: subpage %}

      {% comment %}Break the loop if the count is reached{% endcomment %}
      {% assign count = count | minus: 1 %}
      {% if count == 0 %}{% break %}{% endif %}
    {% endif %}
  {% endfor %}
{% endfor %}