BTrem

11ty nunjucks front matter parsing

11ty lets web authors add a tag to a page in the front matter:

---
tags: cat
---

Or several tags:

---
tags:
- cat
- dog
---

Either way, 11ty will include that page in a collection of articles tagged 'cat'.

I wanted to be able to process my own front matter variables the same way, using either format. Let's consider the following front matter variable:

---
wines:
- Syrah
- Chardonnay
---

Because there's more than one value, wines is an array. I can put each item of the array in a <span> element with a for loop:

{% for grape in wines %}
<span>{{ grape }}</span>
{% endfor %}

The output will be:

<span>Syrah</span><span>Chardonnay</span>

But what if there's only one item in the variable?

---
wines: Syrah
---

If you're using nunjucks as your 11ty template language as I am, the for loop will treat the string as an array of letters:

<span>S</span><span>y</span><span>r</span><span>a</span><span>h</span>

Not what I want. I filed an issue in 11ty's GitHub repo asking for help, and got an answer in less than a day: custom filter! Here's what I added to my .eleventy.js configuration file:

eleventyConfig.addFilter("toArray", function(value) {
if (Array.isArray(value)) {
return value;
}
return [value];
});

I then apply the filter to my front matter variable:


{% for grape in wines | toArray %}
<span>{{ grape }}</span>
{% endfor %}

Now the output is what I want:

<span>Syrah</span>

Thanks to GitHub user Peter deHaan for the idea and the filter code.