very much work in progress enjoy what you see here very much work in progress enjoy what you see here very much work in progress enjoy what you see here very much work in progress enjoy what you see here very much work in progress enjoy what you see here

Nunjucks whitespace control and text file sitemaps

Most of the SEO tools (and WordPress plugins) generate an XML file for the sitemap. However, it’s perfectly fine to keep the sitemap in a simple text file that contains one URL per line.

If you are using Nunjucks as a templating engine, this is one of those rare cases when you have to care about the whitespace control.

As comparison, with the "regular" for loop tag:

{% for post in collections.sitemap %}
{{ post.url }}
{% endfor %}

the output looks like this:


https://www.implenton.com/configure-netlify-to-run-php/

https://www.implenton.com/cube-css-fresh-ideas/

The empty line before the first URL, between the URLs and after the last one, is part of the output. It's not a formatting mistake in this article.

This does not conform with the requirements, as we need exactly one URL per line without empty lines.

You can control the whitespace by adding a minus sign (-) to the start ({%) or end block (%}). If you add it, then it will strip all leading or trailing whitespace.

Here's what worked for me to generate the sitemap.txt:

{%- for post in collections.sitemap -%}
{{ post.url }}
{% endfor -%}

Notice how the beginning of the endfor does not have the - sign, but the rest do.

This resulted in the correct output, without empty lines:

https://www.implenton.com/configure-netlify-to-run-php/
https://www.implenton.com/cube-css-fresh-ideas/
The company of one
of Mészáros Róbert
Hello!