11ty Nested URL Active Links
Last Modified: 08/29/2022 07:05AM GMT+0
Here is a shortcode to set an anchor link as active even
under nested URL paths (ie. /notes
, /notes/foo
, /notes/foo/bar
, etc.):
module.exports = (eleventyConfig) => {
eleventyConfig.addShortcode('isActiveLink', function(url) {
if (url === this.page.url) return '<active-link-class>'
if (url !== '/' && this.page.url.includes(url)) return '<active-link-class>'
return ''
})
}
Make sure to use a normal, non-arrow function so we can bind this
to it
and get the page object in the shortcode callback. (this was added in 11ty v0.11.0).
Example usage:
{% for collection in collections.<collection> %}
<a
href="{{ collection.url }}"
class="{% isActiveLink collection.url %}"
>
{{ collection.url }}
</a>
{% endfor %}