Search code examples
handlebars.jsassemble

How to filter the data from a collection loop?


Im trying to build a related info widget, based on the data from the YAML front-matter. Each page on my collection has some tags associated, and the idea would be to only show those pages who have tags in common with the currently viewed page.

I've managed to get the complete tags outputting the existent pages with the following code:

<section class="see-also">
{{#each tags}}
    <p>In <span class="tag">{{tag}}</span>:</p>
    {{#each pages}}
      <li><a href="{{relative ../../page.dest dest}}">{{data.title}}</a></li>
    {{/each}}
{{/each}}
</section>

Can I apply some sort of filter on {{#each tags}} ?

Thanks.


Solution

  • There's an inArray helper that you can use to test if the current tag is in the tags collection on the page being currently rendered:

    <section class="see-also">
    {{#each tags}}
    {{#inArray ../page.tags tag }}
        <p>In <span class="tag">{{tag}}</span>:</p>
        {{#each pages}}
          <li><a href="{{relative ../../page.dest dest}}">{{data.title}}</a></li>
        {{/each}}
    {{/inArray}}
    {{/each}}
    </section>
    

    You might have to modify the parent path syntax to account for the additional block helper:

    <section class="see-also">
    {{#each tags}}
    {{#inArray ../page.tags tag }}
        <p>In <span class="tag">{{tag}}</span>:</p>
        {{#each ../pages}}
          <li><a href="{{relative ../../../page.dest ../dest}}">{{../data.title}}</a></li>
        {{/each}}
    {{/inArray}}
    {{/each}}
    </section>