Eleventy project logo

Eleventy Extra Spaces in Category List

Print Friendly and PDF

Posted: April 30, 2023 | | Categories: Eleventy

As I built out this site, I added a list of category links to the post page as well as any post listings on the site. I grabbed the code from to do this from A Complete Guide to Building a Blog with Eleventy and it looks like this:

<p>
	<strong>Categories:</strong>
	{% for cat in categories %}
	<a href="/categories/{{ cat | slugify }}">{{ cat }}</a>{% unless forloop.last %}, {% endunless %}
	{% endfor %}
</p>

In this site, I display a little more information on the line as shown below:

Posted {{ post.date | readableDate }}&nbsp;
{% if post.data.categories.length > 0 %}
   in
   {% for cat in post.data.categories %}
     <a href="/category/{{ cat | slugify }}">{{ cat }}</a>
     {% unless forloop.last %}, 
     {% endunless %}
   {% endfor %}
{% endif %}

What I noticed is that on my site, Eleventy put an extra space before the comma for every category. I got a category list, but it didn't format correctly, there was a space before the comma and another one after the comma. Not exactly what I wanted.

Looking at the code, notice how the lines break a little differently than in Ray's example, that's because, I think, I'm using the vscode-liquid plugin for Visual Studio Code and it restructures liquid code and removed the space after the comma. I love the automatic restructuring, but I think that's what broke this for me.

I searched around and couldn't find a solution for this online. I eventually got help on the 11ty Discord. Apparently Liquid helpfully adds a space for you (even though you may not want it to); the solution is to use a dash (-) in the start of the Liquid template to tell Liquid not to add the extra space.

{%- unless forloop.last %},

The complete code block looks like this:

Posted {{ post.date | readableDate }}&nbsp;
{% if post.data.categories.length > 0 %}
   in
   {% for cat in post.data.categories %}
     <a href="/category/{{ cat | slugify }}">{{ cat }}</a>
     {%- unless forloop.last %},
     {% endunless %}
   {% endfor %}
{% endif %}

Next Post: Meta Description and Keywords in Eleventy

Previous Post: Eleventy Enhanced Pagination Navigation Buttons

If this content helps you in some way, please consider buying me a coffee.

Header image: Eleventy Project Home Page.