External Links, Navigation, and the Sitemap in Eleventy
I'm still getting to know Eleventy and slowly adding things to the site.
The first order of business was to add a link to my social media account to the
menu bar. The menu bar is powered by the Navigation plugin. According to the
documentation, adding permalink: false
to the template will keep a
file from being created in the generated output.
---
eleventyNavigation:
key: Label
url: https://external-domain.tld
order: 4
permalink: false
---
However, as soon as I added the
permalink
line, there was an error generating the sitemap. The
documentation on permalinks confirms that no output file will be
created, but also notes it will still be included in collections. As you can
see in the initial template for generating the sitemap (I'm using
eleventy-base-blog
as the basis of my site), it iterates over
collections.all
.
---
permalink: /sitemap.xml
eleventyExcludeFromCollections: true
---
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
{%- for page in collections.all %}
{% set absoluteUrl %}{{ page.url | htmlBaseUrl(metadata.url) }}{% endset %}
<url>
<loc>{{ absoluteUrl }}</loc>
<lastmod>{{ page.date | htmlDateString }}</lastmod>
</url>
{%- endfor %}
</urlset>
When it gets to the external link where permalink
is set to false
, the filter
htmlBaseUrl
throws an error. Since the external link shouldn't be in the sitemap
anyway, testing the truthiness of page.url
before creating the entry does the
trick.
---
permalink: /sitemap.xml
eleventyExcludeFromCollections: true
---
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
{%- for page in collections.all %}
{%- if page.url %}
{% set absoluteUrl %}{{ page.url | htmlBaseUrl(metadata.url) }}{% endset %}
<url>
<loc>{{ absoluteUrl }}</loc>
<lastmod>{{ page.date | htmlDateString }}</lastmod>
</url>
{%- endif %}
{%- endfor %}
</urlset>