Blot

Is it possible to group posts by metadata?

Hello,

I have this in my current template :

<h2>VOLUME 01 : </h2>
      {{#allEntries}}
        {{#tagged.vol_01}}
          <div>
            <a href="{{{url}}}">{{title}}</a>
            <small> - {{date}}</small>
          </div>
        {{/tagged.vol_01}}
      {{/allEntries}}

But all my posts that are tagged vol_01 also have a metadata chapter.

I would like to know if inside my template I could group the vol_01 tagged posts by metadata.chapter.

Thanks

Asked a year ago Edit
1 replies

So you would want all posts with metadata Chapter: 1 to say come before those with Chapter: 2?

It's not possible with the template engine at the moment, however it can be easily achieved with some simple JavaScript. Here's what AI suggests:

  1. First modify your HTML to make it easier to work with in JS:
<h2>VOLUME 01 : </h2>
<div id="chapters">
      {{#allEntries}}
        {{#tagged.vol_01}}
          <div data-chapter="{{metadata.chapter}}">
            <a href="{{{url}}}">{{title}}</a>
            <small> - {{date}}</small>
          </div>
        {{/tagged.vol_01}}
      {{/allEntries}}
</div>

Then add the JavaScript below to sort the divs:

<script>
document.addEventListener("DOMContentLoaded", function() {
  const container = document.getElementById('chapters');
  // Get NodeList, convert to array
  const divs = Array.from(container.querySelectorAll('div[data-chapter]'));
  // Sort numerically based on data-chapter attribute
  divs.sort((a, b) => {
    const aVal = a.getAttribute('data-chapter');
    const bVal = b.getAttribute('data-chapter');
    // Try to parse as numbers, fallback to string compare
    const aNum = parseFloat(aVal);
    const bNum = parseFloat(bVal);
    if (!isNaN(aNum) && !isNaN(bNum)) {
      return aNum - bNum;
    }
    return aVal.localeCompare(bVal, undefined, {numeric: true, sensitivity: 'base'});
  });
  // Remove all original divs
  divs.forEach(div => container.appendChild(div));
});
</script>
a year ago Edit

Your reply