Use an Eleventy filter as an if statement

18 Apr 2021 in TIL

On this blog, til is a special category that I wanted to render differently. It has it's own template and does not follow the standard /category/:slug URL pattern. It lives at /til instead.

This meant that anywhere I output a category link (e.g. in the post sidebar on the right or on a topic page) I needed to write the same if statement repeatedly.

Instead of duplicating the logic multiple times, I extracted it to my .eleventy.js config file as a filter:

javascript
eleventyConfig.addShortcode("category_url", async function (category) {
const slug = slugify(category, { lower: true });
if (slug === "til") {
return "/til";
}
return "/category/" + slug;
});

This means that anywhere I need to output a category link, I can now call this filter:

html
<a href="{% category_url post.data.category %}" class="meta-tag">
{{post.data.category}}
</a>

If you find yourself writing the same logic repeatedly, adding it as a filter is a great way to DRY your templates.