Collecting Pages from a collection by keyword

I have a website built around three ‘collections’. Each page of the collection will have some keywords, and I would like to create a page (outside the collection) that collects the keywords together, so, e.g., makes a list of the keywords, like this:


  • key word 1
  1. hyper link to page A: Page A uses keyword 1
  2. hyper link to page E: Page E uses key word 1
  • key word 2
  1. hyper link to page A: page A uses keyword 2
  2. hyper link to page B: page B uses keyword 2
  3. hyper link to page G: page G uses keyword 2
  • key word 3

and so on.
An additional complication is that there are three different collections containing the pages I want to parse in this way, but I want to make a single list of keywords of this kind that ‘stiches together’ all three collections.

I started out by putting some sample keywords in the YAML headers of the first few pages of one of the three collections (collection named GPI_chapters) and tried the following code, from a Stack Overflow answer to build this page, but it’s quite inadequate.

{% assign tags =  site.GPI_chapters | map: 'keywords' | uniq %}
{% for tag in tags %}
  <h3>{{ tag }}</h3>
  {% for page in site.GPI_chapters %}
    {% if page.keywords contains tag %}
    <a href="{{site.baseurl}}{{page.url}}">{{ page.title }}</a>
    {% endif %}
  {% endfor %}
{% endfor %}

Possibly the code you copied from SO was for an HTML file not Markdown. The odd appearance of the output is due to the mix of Markdown and HTML, specifically the indentation of the <h2>{{ page.title }}</h2> and {{ page.content }} cause those to be rendered as code blocks.

hmm. My site uses what you’re calling a ‘mix of Markdown and HTML’ and this doesn’t cause any problems, for example on this page.

For example, when this code is interpreted as Markdown:

<p>This is a test</p>
    <p>This is a test</p>

It produces the following result (quoted for exposition). In Markdown, the 4 spaces before the second <P> create a code-block. Markdown isn’t a pure super-set of HTML, so you will sometimes get unexpected results when copy-n-pasting HTML into Markdown:

This is a test

<p>This is a test</p>

The Markdown generated HTML is:

<p>This is a test</p>
 <pre><code><p>This is a test</p></code><pre>

Okay, I feel silly for not having known this. Thank you for helping me out! Now I know not to use too much indentation when writing for loops.