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:
{% raw %}
{% for post in collections.sitemap %}
{{ post.url }}
{% endfor %}
{% endraw %}
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 to 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 ({% raw %}{%{% endraw %}) or end block ({% raw %}%}{% endraw %}). If you add it, then it will strip all leading or trailing whitespace.
Here’s what worked for me to generate the sitemap.txt:
{% raw %}
{%- for post in collections.sitemap -%}
{{ post.url }}
{% endfor -%}
{% endraw %}
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/